Rails嵌套了has_many关联,如何获得所有孩子中的最后5个?

Ran*_*uin 0 ruby-on-rails

比方说

Post has_many :comments
Run Code Online (Sandbox Code Playgroud)

然后

Comment has_many :ratings
Run Code Online (Sandbox Code Playgroud)

如何获得每个帖子的最后5条评论评分?我一直在考虑只循环浏览每个帖子的评论,但这不能解决最后5部分。

编辑:作为对J.的回应,因为我似乎无法格式化注释字段内的代码

您可以嵌套:through关系吗?说...

class Category < ActiveRecord::Base
  has_many :posts
  has_many :comments, :through => posts
  has_many :ratings, :through => comments
end

class Post < ActiveRecord::Base
  belongs_to :category
  has_many :comments
  has_many :ratings, :through => comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
  has_many :ratings
end

class Rating < ActiveRecord::Base
  belongs_to :comment
end
Run Code Online (Sandbox Code Playgroud)

Jef*_*tte 5

您可以使用标准ActiveRecord来执行此操作find :all, :order => "created_at desc", :limit => 5。我认为您可以像这样包装这是一个named_scope:

class Rating < ActiveRecord::Base
  named_scope :most_recent,  lambda { |n| { :conditions => [:order => 'created_at desc', 
                                            :limit => n] }

end

and in your controller:
@recent_ratings = @comment.ratings.most_recent(5)
Run Code Online (Sandbox Code Playgroud)