How to update the extra field of relationship table when use have_many :throuth effectively

I defined the relationship of two tables as below:

Programme(id,code,name)
Course(id,code,name)
ProgarmmeCourse(id,programme_id,course_id,status)

class Programme < ActiveRecord::Base
has_many :programme_courses,:dependent=>:destroy
end

class ProgrammeCourse < ActiveRecord::Base
belongs_to :programme
belongs_to :course
end

class Course < ActiveRecord::Base
has_many :programmes,:through=>:programme_courses
end

there are a list of courses belong to a programme on Programme’s update
page, i can update the status(enable/disable) of course belong to the
programme or add a new course from a list of course.

how to save the field of status(enable/disable) effectively after save
Programme?

Could you please give me a sample?
Thanks for your help


View this message in context:
http://www.nabble.com/How-to-update-the-extra-field-of-relationship-table-when-use-have_many-%3Athrouth-effectively-tp19952307p19952307.html
Sent from the RubyOnRails Users mailing list archive at Nabble.com.

What you’re asking is how to set attributes on the join model. Josh
Susser
covered one way to do this here:
has_many :through - New on edge: Magic join model creation with
his
push_with_attributes method on the association. You use it like this:

class Programme < ActiveRecord::Base
has_many :programme_courses,:dependent => :destroy
has_many :courses, :through => :programme_courses do
def push_with_attributes(element, attributes = {})
ProgrammeCourse.send :with_scope, {:create => attributes} do
self << element
end
end
end
end

To create the relationship between a Course and a Programme with a
status
value on the join model you can use it like this:
c = Course.find :first
p = Programme.find :first
p.courses.push_with_attributes(c, :status => ENABLED) # Or whatever
you’re
setting status to

To set the value on the join model after it’s been created, you have to
do
something more like
ProgrammeCourse.find_by_programme_id_and_course_id(p,
c).update_attribute
:status, DISABLED # Or whatever you’re setting status to

Of course you should refactor these for simplicity in your application.
There are probably nicer ways to do this nowadays but I’m not sure what
they
are.

Cheers,
Morgan.

2008/10/13 guofeng.ma [email protected]

class Programme < ActiveRecord::Base
end


View this message in context:
http://www.nabble.com/How-to-update-the-extra-field-of-relationship-table-when-use-have_many-%3Athrouth-effectively-tp19952307p19952307.html
Sent from the RubyOnRails Users mailing list archive at Nabble.com.

Morgan G. - Just Landed
General Tel: +34 91 590 2611
[email protected]

http://www.justlanded.com - Helping people abroad!
30 countries, in up to 8 languages, more to come…