Reputation: 661
Hi thanks for viewing my question. I am trying to figure out if there are any performance benefits (or any other benefits) to creating more instance variables in a controller rather than accessing relationships in the view with the model methods. Here's an example of what I mean
You could go this way:
# posts_controller.rb
def show
@post = Post.find(id)
@comments = @post.comments
end
# posts/show.html.erb
<%= @comments.each do |c| %>
...
Or, alternatively:
# posts_controller.rb
def show
@post = Post.find(id)
end
# posts/show.html.erb
<%= @post.comments.each do |c| %>
...
Does either of these approaches have a performance benefit? When should you decide to create an additional instance variable rather than accessing data through the model's methods in the view? Any other reason to pick one over the other? Is there a better approach? Asking for educational purposes and lack of Google answers.
Thanks!
Upvotes: 1
Views: 121
Reputation: 6121
Any call which queries the db is not recommended from views, that's the reason it is separated M-V-C, it is controller who should query the db and provide readymade object to the view using instance variables
.
In the mentioned example above, although first is better option, it will query db
twice, in such cases you should include the comments in the same call.
def show
@post = Post.find(id).includes(:comments)
end
then in your view,
<%= @post.comments.each do |c| %>
is good because it has preloaded
comments
beforehand..
Fetching all required data in controller also helps in reducing N+1
query problems..
Upvotes: 1