Answer the question
In order to leave comments, you need to log in
How to extract the number of entries and the last entry in a has_many through association?
There are three models:
class Category < ActiveRecord::Base
has_many :posts, dependent: :destroy
has_many :comments, through: :posts, dependent: :destroy
end
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
belongs_to :category
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :category
end
def show
@category = Category.includes(:comments, :posts).find(params[:id])
end
<h1>@category.name</h1>
<% @category.posts.each do |post| %>
<%= post.name %>
<%= post.comments.count %> <!-- либо post.comments.size, работаем с массивом, не делаем лишние запросы -->
<%= post.comments.last.body %>
<% end %>
Answer the question
In order to leave comments, you need to log in
If you don’t want to pull everything out, then just make separate requests for the number of comments and the last one and remove from comments from includes.
@comment_cnt = Comment.where(post_id: @category.post_ids)).group(:post_id).count
@comment_last = Comment.where(post_id: @category.post_ids).group(:post_id).having('id = MAX(id)')
You are not saying something
parent.children.last will only load 1 object per 1 request to the parent and 1 request to the child
parent.children.count will make 1 request to the parent and 1 request to count to the child
of all children (comments in your case) load won't
or, I suspect, since I don't see your problematic queries, I can only guess:
try to include/join comments to posts, not categories@category.posts.includes(:comments).each do |post|
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question