【问题标题】:Rails accept_nested_attributes still throws "Can't mass-assign protected attributes"Rails accept_nested_attributes 仍然抛出“无法批量分配受保护的属性”
【发布时间】: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


    【解决方案1】:

    正如错误所说,您只需将basket_items_attributes 添加到您接受的属性列表中。

    所以你有

    attr_accessible :user_id, :basket_items_attributes
    

    在您的 basket.rb 文件的顶部

    【讨论】:

    • 谢谢。这解决了它。本可以发誓我曾尝试将此作为解决方案,但一定是与其他混乱的解决方案混为一谈。
    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    相关资源
    最近更新 更多