【发布时间】:2013-04-19 15:27:52
【问题描述】:
我想我要么遗漏了一些非常简单的东西,要么遗漏了一些非常模糊的东西。希望有人能帮我发现或解释我的木偶戏。
好的,所以有两个模型,Basket 和 BasketItem。
我已将 Basket 设置为 accept_nested_attributes :basket_items,目的是在 Basket 的编辑视图中使用 fields_for。
但是当它跑起来时它仍然会尖叫
Error: Can't mass-assign protected attributes: basket_items_attributes
对于这个问题,如果我在控制台中手动使用一个或两个 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"}
})
我已确保在接受嵌套属性之前定义的关联,子模型也具有可访问的适当属性,尝试删除嵌套数据的其他属性,大量摆弄无济于事。
basket.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
basket_item.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
【问题讨论】:
标签: ruby-on-rails model nested-attributes