Model.create()使用只读属性抛出错误

时间:2012-12-14 01:59:20

标签: ruby-on-rails activerecord

我在rails(简化)中有以下模型:

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

根据文档,attr_readonly应该允许在创建时设置属性,但不能在更新时设置。

然而,当我这样做时:

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

我收到此错误:

Can't mass-assign protected attributes user, brand

我错过了什么?

1 个答案:

答案 0 :(得分:3)

如果您想要分配用户和类似的品牌关联,您必须将它们定义为可访问的属性:

attr_accessible :user, :brand

否则,您可以像这样分配它们:

Model.create({:user => user, :brand => brand }, :without_protection => true)