Has_many through question

Hi, I have a fairly typical has_many, through setup with a bit of a
twist.

class Course < ActiveRecord::Base

has_many :placements
has_many :students, :through => :placements

end

class Student < ActiveRecord::Base

has_many :placements
has_many :courses, :through => :placements

end

class Placements < ActiveRecord::Base

belongs_to :course
belongs_to :student

end

So with this I could grab all the students for a course by:

@students = @course.students

Everything is fine so far, but here is the twist. I have to narrow
things
down by some data on the placements table. Let’s say I have a column
called
“placed_by” on “Placements”

How would I retrieve all of the students for a course if I only wanted
to
see those who were placed by “Bob” for example?

two possible ways:

  1. if the condition has to be met every time:

has_many :students, :through => :placements, :conditions => {:placed_on
=> ‘you_value’}

  1. more likely and more flexible the “association extensions”:

has_many :students, :through => :placements do
def placed_by(who)
find_all_by_placed_by(who)
end
end

can be called:
@students = @course.students.placed_by(who_id)

Thanks, #2 nails it! Would it be roughly the same if there were two or
three unrelated fields on there? Something like:

has_many :students, :through => :placements do
def find_by(who, when)
find(:all, :conditions =>[‘placed_by = ?, created_on >= ?’,who,
when])
end
end

@students = @course.students.find_by(who_id, datetime)

On Dec 3, 2007 1:53 PM, Thorsten M.
[email protected]

Joe C. wrote:

Thanks, #2 nails it! Would it be roughly the same if there were two or
three unrelated fields on there? Something like:

has_many :students, :through => :placements do
def find_by(who, when)
find(:all, :conditions =>[‘placed_by = ?, created_on >= ?’,who,
when])
end
end

@students = @course.students.find_by(who_id, datetime)

On Dec 3, 2007 1:53 PM, Thorsten M.
[email protected]

yes, you can place any code you like in this method, as long as it
returns something that’s usable as a student (in this case) :wink:

you can use the finder functions or find_by_sql for really hard work
in theory it should even be possible to return an array of hashes, that
contain all the necessary columns as keys
[{name => “student1”, :location => “Washington” …}, {:name => “student
two”, …}]
but i never tried that last one myself

What about something a little different?
Is there a way to process 2 levels deep?
so @all_courses = @students.courses
In SQL that could be an IN() statement composed of student IDs.

On Dec 3, 2:27 pm, Thorsten M. [email protected]