:limit => Parent / Child Relationship

Hi all,

I trying to find the best way to do the following and I’ll use a blog
with comments for an example.

Blog has many comments
Comments belongs to blog

My question is how to limit the number of comments (child) records read
for each blog (parent) record. Most of the solutions I’ve come up with
are limiting the number of records displayed within the views but the
select statement on the comments table still gets all of them. My goal
is to only show the 10 most recent comments for the blog entry if there
are X + 10 comments, but I still want to be able to display all comments
if the user chooses to. I want to retrieve the least amount of records
possible to save on performance.

I’m stumped on where to implement this. In the model? The controller?
And still make it DRY enough.

Any thoughts would be greatly appreciated.

Sam

try using limit in the has_many method call

has_many :comments
has_many :recent_comments, :class_name => “comment”, :order =>
“created_at
DESC”, :limit => 10

Then in your controller / view / whatever

@my_blog.recent_comments # => returns a result of the 10 (or upto 10 )
most
recent comments

Daniel,

Thanks! That worked like a charm. The only change I had to make was to
capitalize the :class_name string.

Sam

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs