2010-06-09 44 views
0

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

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 
+0

要回答你的编辑,我米不知道你可以做到这一点。至少我从来没有这样做过......在我看到你的编辑后,我实际上正在尝试做,但没有成功。 – 2010-06-09 19:11:56

+0

人,我想知道为什么。嵌套这种关系听起来应该更常见。我应该重新考虑我的数据模型吗? – Randuin 2010-06-09 19:34:05

+0

我不是说这是不可能的,我只是不能在这里做...你应该尝试看看你得到了什么:] – 2010-06-09 20:04:35

回答

-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 
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) 
4

您可以使用标准的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) 
相关问题