Looking at the documentation on associations, I've managed to set up my classes to use has_many, :through
. However, I can't seem to find any example on how to actually use the association.
My User
model has_many :attendees
and has_many :events, through: :attendees
. My Event
model has_many :attendees
and has_many :users, through: :attendees
.
Attendee model:
class Attendee < ActiveRecord::Base
attr_accessible :status
validates_inclusion_of :status, in: [:performing, :invited, :going, :maybe]
belongs_to :user
belongs_to :event
def status
read_attribute(:status).to_sym
end
def status=(value)
write_attribute(:status, value.to_s)
end
end
I tried using the following code:
at1 = Attendee.new(user: u1, event: e1)
at1.status = :invited
at1.save
Unsurprisingly, I get a mass assignment error with user
and event
. It seems besides the point to declare attr_accesible
for user
and event
though. how would I use the association here, and set the custom status
attribute?
It's absolutely not beside the point to declare attr_accessible
. That's what you're missing.
Keep in mind attr_accessor
is something else. For more on this, check: Difference between attr_accessor and attr_accessible
Also keep in mind that attr_accessible
has been deprecated in Rails 4 in favor of Strong Parameters , effectively moving all whitelisting of attributes from the models to the controllers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.