0

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?

Marcelo De Polli
  • 28,123
  • 4
  • 37
  • 47
FeifanZ
  • 16,250
  • 7
  • 45
  • 84

1 Answers1

0

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.

Community
  • 1
  • 1
Marcelo De Polli
  • 28,123
  • 4
  • 37
  • 47
  • Thanks! As I'm learning Rails, I suppose I expected Rails to handle the association attributes automatically, and I was just not seeing how to do it. Nice to have learned something :) And thanks for the Rails 4 notice! – FeifanZ Jun 20 '13 at 02:05
  • 1
    I know it may look a bit weird that you have to manually whitelist your attributes. But it's a security feature, and it was intentionally implemented like that by the Rails core group. Strong Parameters are even more secure, and better aligned to the MVC principles. If you can start off by developing your app in Rails 4, it's going to be worth your while in the long run. – Marcelo De Polli Jun 20 '13 at 02:08
  • Our app is started in 3.2 and deployed as such on Heroku. I'd love to learn with Rails 4, but given that 3.2 is more mature (and hence more resources out there), I think it's a good place to start. Still, thanks for the help! – FeifanZ Jun 20 '13 at 02:37