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 に答える