0

I have the following model in rails (simplified):

class Phone < ActiveRecord::Base
  include ActiveModel::Validations
  belongs_to :user
  belongs_to :brand
  attr_readonly :user, :brand
  attr_accessible :model, :phone_number

  validates :user, :presence => true
  validates :brand, :presence => true
  validates :model, :presence => true
  validates :phone_number, :presence => true
end

According to the documentation, attr_readonly should allow attributes to be set at creation, but not at update.

However, when I do this:

Phone.create(:user => <existing_user>, :brand => <existing_brand>, :model => "Galaxy", :phone_number => "555-433-5678")

I get this error:

Can't mass-assign protected attributes user, brand

What am I missing?

0

1 Answer 1

3

If you want to assign a user and a brand association like that, you must define them as being accessible attributes:

attr_accessible :user, :brand

Otherwise, you can assign them like this:

Model.create({:user => user, :brand => brand }, :without_protection => true)
Sign up to request clarification or add additional context in comments.

2 Comments

Ryan, it's a bit more complicated than that, since the model has two associations (I updated the example). Even if I use the association builder for one of the belongs_to associations, I get the error for the other association.
Ryan - setting them as accessible defeats the purpose a bit. I want the associations to be set at creation and then never altered; how would I achieve that if not via a attr_readonly setting?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.