Get n most recent records in a foreign key's table (Rails ActiveRecord)

Simple question here.

I have a User table. Each User has many Goals. Each Goal has many Objectives. Each Objective has a created_at column.

I'd like to get the 10 most recent Objectives created for a User (regardless of any specific Goal), but I'm not sure how to structure the ActiveRecord query.

I know how to get the 10 most recent Objectives in general. You would do the following:

Objective.find(:all, :limit => 10, :order => 'created_at desc')

But I don't know how to get the 10 most recent Objectives for a specific User (i.e. going from User -> Goal -> Objective).

How do I do this?

Upvotes: 0

Views: 417

Answers (1)

Anthony Alberto
Anthony Alberto

Reputation: 10405

Use a has_many :through

class User < ActiveRecord::Base
  has_many :goals
  has_many :objectives, :through => :goals
end

Now, whenever you do user.objectives you'll get all objectives of the user regardless of the goal.

So in order to get the latest objectives :

user = User.find(your_id)
latest_objectives = user.objectives.order('created_at desc').limit(10)

Upvotes: 2

Related Questions