我提交的表单存在以下问题:
未填写的参数传递and
找不到所传递的关联模型属性。
表格:
...
<% PrintLocation.all.each.with_index do |print_location, index| %>
<%= print_location.title %>
<%= f.fields_for :shop_product_print_files_attributes, index: index, multiple: true do |a| %>
<%= a.text_field :print_file %>
<%= a.hidden_field :print_location_id, value: print_location.id %>
<%= a.hidden_field :shop_product_id, value: shop_product.id %>
<% end %>
<% end %>
...
传递参数:
, "shop_product_print_files_attributes"=>{"0"=>{"print_file"=>"a", "print_location_id"=>"1", "shop_product_id"=>"45"}, "1"=>{"print_file"=>"", "print_location_id"=>"2", "shop_product_id"=>"45"}, "2"=>{"print_file"=>"", "print_location_id"=>"3", "shop_product_id"=>"45"}, "3"=>{"print_file"=>"", "print_location_id"=>"4", "shop_product_id"=>"45"}, "4"=>{"print_file"=>"", "print_location_id"=>"5", "shop_product_id"=>"45"}, "5"=>{"print_file"=>"", "print_location_id"=>"6", "shop_product_id"=>"45"}},
型号:
class ShopProductPrintFile < ApplicationRecord
belongs_to :shop_product
belongs_to :print_location
end
class PrintLocation < ApplicationRecord
has_many :shop_products, through: :shop_product_print_files
has_many :shop_product_print_files
accepts_nested_attributes_for :shop_product_print_files
end
class ShopProduct < ApplicationRecord
...
has_many :shop_product_print_files
has_many :print_locations, through: :shop_product_print_files
accepts_nested_attributes_for :shop_product_print_files
end
控制器:
def new
@shop_product = ShopProduct.new
@shop_product.shop_product_print_files.build
end
def create
@shop_product = ShopProduct.new(shop_product_params)
@shop_product.shop_product_print_files.build(print_location_id: params["shop_product"]["shop_product_print_files_attributes"]["print_location_id"])
shop = Shop.find(params["shop_product"]["shop_id"])
product = Product.find(params["shop_product"]["product_id"])
@shop_product.product_id = product.id
@shop_product.shop_id = shop.id
respond_to do |format|
if @shop_product.save!
...
end
end
def update
@shop_product = ShopProduct.find_by(store_variant_id: params["shop_product"]["store_variant_id"])
@shop_product.shop_product_print_files.build(shop_product_id: @shop_product.id, print_location_id: params["shop_product"]["shop_product_print_files_attributes"]["print_location_id"])
@product = Product.find(params["shop_product"]["product_id"])
respond_to do |format|
if @shop_product.update(shop_product_params)
...
end
end
private
def shop_product_params
params.require(:shop_product).permit(...., :shop_product_print_files_attributes => [:id, :print_file, :print_location_id, :shop_product_id])
end
错误:
Shop product print files print location must exist
最大的问题是找不到print_location,但是为什么不呢?
除此之外,为什么即使print_file
为空也要发送所有参数?
在我没有使用each.with_index
和表单中使用index: index
之前。这样,表单将提交并创建shop_product_print_files
,但是问题在于它只会传递PrintLocation循环中的最后一个值,"6"
和1-5
将被废弃。当我安装使用索引代码时,一切都会通过,但一切都会通过,并且不会因上述错误而被保存。
我该怎么做,才能使通过的参数不为空,并找到它们?