Rails嵌套has_many关联,如何得到,比方说,最后5个孩子?

时间:2010-06-09 16:46:28

标签: ruby-on-rails

让我们说

Post has_many :comments

那个

Comment has_many :ratings

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

编辑:回应J.因为我似乎无法在评论字段中格式化代码

你能否通过关系嵌套:?说...

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

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:4)

我相信以下内容可能有用......如果不是,请告诉我:]

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

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

class Rating < ActiveRecord::Base
   # I'm assuming you have the created_at column
   default_scope :order => 'created_at DESC'
end

# controller
@last_five_ratings = @post.ratings.all(:limit => 5)

答案 2 :(得分:-4)

最后,我能够在Rails 3下得到我想要的东西

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

  def ratings
    Rating.category_ratings(self)
  end
end

class Rating < ActiveRecord::Base
  belongs_to :comment

  scope :category_ratings, lambda { |c|
    joins(:comment, 'INNER JOIN `posts` ON `posts`.`id` = `comments`.`post_id`').
    where(:posts => {:category_id => c.id}).
    select('DISTINCT `comments`.*')
  }
end