Вложенная в Rails ассоциация has_many, как получить, скажем, последние 5 из всех детей? - PullRequest
0 голосов
/ 09 июня 2010

Допустим, что

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 ]

5 голосов
/ 09 июня 2010

Вы можете сделать это с помощью стандартной 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)
4 голосов
/ 09 июня 2010

Я верю, что что-то вроде следующего может сработать ... Дайте мне знать, если это не так:]

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)
0 голосов
/ 10 июня 2010

В конце я смог получить то, что искал, с помощью 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...