views:

44

answers:

3

Let's say that

Post has_many :comments

and that

Comment has_many :ratings

How can I grab the last 5 comment ratings for each Post? I've been thinking of just looping through comment for each post but that wouldn't solve the Last 5 part.

EDIT: In response to J. since I can't seem to format code inside the comments field

Would you be able to nest the :through relationship? say...

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
A: 

I believe something like the following may work... Let me know if it doesn't :]

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)
j.
A: 

You can do this with a standard ActiveRecord: find :all, :order => "created_at desc", :limit => 5. I think you can wrap this is a named_scope like so:

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)
Jeff Paquette
A: 

At the end I was able to get what I was looking for with this under 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
Randuin