0

我在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

我错过了什么?

4

1 回答 1

3

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

attr_accessible :user, :brand

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

Model.create({:user => user, :brand => brand }, :without_protection => true)
于 2012-12-14T02:03:19.200 回答