嵌套表单的UnknownAttributeError

时间:2016-04-18 11:41:24

标签: ruby-on-rails-4

我有两个模型:

客户:

has_many :products, :dependent => :destroy
accepts_nested_attributes_for :products, reject_if: proc { |attributes| attributes['product_id'].blank? }

产品:

belongs_to :customer

产品控制器:

def product_params
    params.require(:product).permit(:name, :first_build)
end

客户控制员:

    def customer_params
        params.require(:customer).permit(:first_build, :name, :product_id, 
                                  products_attributes: [:first_build, :customer_id])
    end

所以在客户控制器中我这样做

@customer.products.build(:first_build => true)

但我收到此错误

unknown attribute 'first_build' for Prodcut

但是当我这样做时@customer.products.build(:name => "test product name")

它完美无缺,没有任何错误。这里需要注意的一点是,first_build不是products表中的列。

1 个答案:

答案 0 :(得分:1)

如果要传递表中没有的属性,可以创建一个"临时"属性不会存储在表中,但在对象在内存中时可用。

class Product < ActiveRecord::Base

  attr_accessor :first_build
  ...

end