chuck w
chuck w

Reputation: 1761

Eager Loading First Association

I have a Story model and a Post model. Each story has many posts, and each post belongs to a story.

When I load a specific story into memory from the DB I want to eager load that story's most recent post. Here's how I do it now:

@story = Story.includes(:posts).find(params[:story_id])
@latest_post = @story.posts.first  #Note, story.posts :order => "created_at DESC"

This works, but it doesn't seem very effecient to load all of a story's posts into memory when I only need the most recent post. Is there a way to limit the includes to only eagerly load the first post? Should I even be worrying about this?

Upvotes: 0

Views: 219

Answers (1)

MurifoX
MurifoX

Reputation: 15109

Use SQL order by, join and limit. An ActiveRecord query would look like this:

@latest_post = @story.include(:posts).order("created_at DESC").limit(1)

This will create a join with posts, order by newest posts and just fetch one.

Upvotes: 1

Related Questions