In a scenario with 1->N->N assocations. For example: Post->Comments->Votes (votes will be list of names of people who voted on the comment). To display a page the query with includes might look like:
@post = Post.where(:id => 100).includes({:comments => :votes}).first
I am starting to add caching support. Which means if the comments partial is already cached I will not need to run include the comments/votes all the time. So I wonder if there is a way to make the code appear like:
# controller
@post = Post.find(100)
# view
<% cache('comments', @post.last_comment_time do %>
<% @post.includes({:comments => :votes}).comments.each do |comment| # ???? %>
<% end %>
Running the “post-query” includes, will “fill in” the associations. So @post.comments will be populated and each comment will include all the votes. Is there a way to achieve this?
P.S. I am aware the view is not the best place to run the query, this is just an example.
in latest releases of rails, all the finder-methods return a proxy object, that will only trigger a database-call once you send it some iterator-method like
allorfirstin your case. this is why you can chain all the calls likePost.where.order.sort.bla.it’s not possible though to load the post model and use an
includescall later.includesworks by using ajoincall on the relations that get loaded with the model instance, so that you have just one database-call instead of one for each relation.executing active_record code in your view is also a bad practice. the data-retrieval is the responsibility of the controller, not the view.