2010-06-09 43 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) 
相關問題