本当に単純なものか、本当にあいまいなものが欠けていると思います。誰かが私のためにそれを見つけたり、私のマペットを説明したりできることを願っています.
わかりました。Basket と BasketItem の 2 つのモデルがあります。
バスケットの編集ビューで fields_for を使用するつもりで、バスケットを accept_nested_attributes :basket_items に設定しました。
しかし、駆け上がると、それはまだ叫びます
Error: Can't mass-assign protected attributes: basket_items_attributes
この質問のために、1つまたは2つのbasket_item属性を使用してコンソールで手動のbasket.update_attributesを実行すると、同じ問題に煮詰めました。したがって、ビューやコントローラーの問題ではなく、モデルの問題であることはわかっています。例えば:
basket.update_attributes("basket_items_attributes"=>[{"qty"=>"1", "id"=>"29"}, {"qty"=>"7", "id"=>"30"}])
または同様に、 fields_for のようなハッシュを使用すると、
basket.update_attributes( "basket_items_attributes"=>{
"0"=>{"qty"=>"1", "id"=>"29"},
"1"=>{"qty"=>"7", "id"=>"30"}
})
私は、accepts_nested_attributes_for の前に関連付けが定義されていること、子モデルにもアクセス可能な適切な属性があること、ネストされたデータの追加の属性を削除しようとしたことを確認しました。
バスケット.rb
class Basket < ActiveRecord::Base
has_many :basket_items
attr_accessible :user_id
accepts_nested_attributes_for :basket_items
belongs_to :user
def total
total = 0
basket_items.each do |line_item|
total += line_item.total
end
return total
end
# Add new Variant or increment existing Item with new Quantity
def add_variant(variant_id = nil, qty = 0)
variant = Variant.find(variant_id)
# Find if already listed
basket_item = basket_items.find(:first, :conditions => {:variant_id => variant.id})
if (basket_item.nil?) then
basket_item = basket_items.new(:variant => variant, :qty => qty)
else
basket_item.qty += qty
end
basket_item.save
end
end
バスケットアイテム.rb
class BasketItem < ActiveRecord::Base
belongs_to :basket
belongs_to :variant
attr_accessible :id, :qty, :variant, :basket_id
def price
variant.price
end
def sku
return variant.sku
end
def description
variant.short_description
end
def total
price * qty
end
end