Bryce
Bryce

Reputation: 2872

Model.create() throws errors with readonly attributes

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?

Upvotes: 0

Views: 145

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107718

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)

Upvotes: 3

Related Questions