Lai Yu-Hsuan
Lai Yu-Hsuan

Reputation: 28081

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?

Upvotes: 1

Views: 1124

Answers (2)

Hugo Dozois
Hugo Dozois

Reputation: 8420

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.

Upvotes: 1

jbarket
jbarket

Reputation: 882

There'll be no real performance difference. It's just a matter of style and code separation.

Upvotes: 0

Related Questions