Ruby嵌套表单
实际上,在保存它必须保存,但我收到错误,并试图找出我错误的错误。
请帮我解决这个错误。
提前致谢。
调节器
def new @fooditem = Fooditem.new 3.times { @fooditem.fooditemprices.build} end #Creating Food Items def create @fooditem = Fooditem.new(fooditem_params) if @fooditem.save flash[:success] = "Food item created successfully." redirect_to fooditems_path else render 'new' end end
楷模)
class Fooditem < ApplicationRecord has_many :fooditemprices, dependent: :destroy accepts_nested_attributes_for :fooditemprices, reject_if: lambda {|attributes| attributes['price'].blank?}, allow_destroy: true end class Fooditemprice < ApplicationRecord belongs_to :fooditem validates :size, presence: { message: "Size must exists." } validates :price, presence: { message: "Price must exists." } end
表格数据
错误
fooditem must exist
Params收到了
"fooditem"=>{"name"=>"Food Item Name", "bdescription"=>"Food Item description of brief", "ddescription"=>"Food Item description of detailed", "priority"=>"1", "foodtype_id"=>"1", "foodcategory_id"=>"1", "fooditemprices_attributes"=>{ "0"=>{"size"=>"Full", "price"=>"120", "weight"=>"200", "weight_in"=>"Grams"}, "1"=>{"size"=>"Full", "price"=>"80", "weight"=>"120", "weight_in"=>"Grams"}, "2"=>{"size"=>"Full", "price"=>"50", "weight"=>"60", "weight_in"=>"Grams"}}, "sku"=>"", "active"=>"1"}, "commit"=>"Create Food Item"}
您正在使用Rails 5,因此默认belongs_to
要求关联记录必须存在。
尝试在您的关联中添加inverse
,如下所示:
class Fooditem < ApplicationRecord has_many :fooditemprices, dependent: :destroy, inverse_of: :fooditem end class Fooditemprice < ApplicationRecord belongs_to :fooditem, inverse_of: :fooditemprices end
它应该工作。