Search code examples
ruby-on-railsrails-activerecordseparation-of-concerns

Rails - query model in view or controller?


The User has many Folders. To implement the index action of Folder, I can query the folders of specific user in controller:

class FoldersController < ApplicationController
  def index
    @folders = current_user.folders
  end
end

#app/views/folders/index.html.haml
- @folders.each
...

But I can skip the controller as well:

#app/views/folders/index.html.haml
- current_user.folders.each
...

Of course the former is much more elegant. But are they substantially different? I mean, whether they have different performances or output different results sometimes?


Solution

  • It will probably take the same time, but you should not have logic in your views.

    You should do it in your controller as you stated in your first of two examples. The folder view display folders, it doesn't have to know that it is the current user's folders.

    That way, you can do an admin action where you would retrieve let say all the folders and pass it to the same view in the variable "folders". The view doesn't care whose folder it just represents whatever folder list you pass to it.