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
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.