Has_many through - how to use middle model's info?

Hey,

How can I use the information in the “middle” table of a :has_many
through relationship? Here’s an example:

Club and Student have a :has_many through relationship with each other.

class Club < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :students, :through => :memberships
end

class Student < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :clubs, :through => :memberships
end

middle model

class Membership < ActiveRecord::Base
belongs_to :student
belongs_to :club
end

Here is the table for “memberships”
id - integer
club_id - integer
student_id - integer
joined_on - datetime

If I have @club_id, and I want to find all students that joined that
club on a certain date, how can I do that?

How can I do something like this
Club.find_by_id(@club_id, :include => :students)
and specify the “joined_on” date?

Thanks for any help.

To get the memberships, you can:

@memberships = @club.memberships.all(:conditions => {:created_on =>
date})

Then now you simply have to get the students of each membership.

On Thu, Aug 14, 2008 at 3:04 AM, Joe P.
[email protected] wrote:

has_many :students, :through => :memberships
belongs_to :club

How can I do something like this
Club.find_by_id(@club_id, :include => :students)
and specify the “joined_on” date?

Thanks for any help.

Posted via http://www.ruby-forum.com/.


Ramon T.

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