目标:以一种形式更新多个记录。每条记录通过shop_product_print_file具有许多print_locations
有6个可能的打印位置
型号:
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 ShopProductPrintFile < ApplicationRecord
belongs_to :shop_products
belongs_to :print_locations
belongs_to :image_file
end
class ShopProduct < ApplicationRecord
...
has_many :shop_product_print_files
has_many :print_locations, through: :shop_product_print_files
accepts_nested_attributes_for :print_locations
accepts_nested_attributes_for :shop_product_print_files
...
end
class ImageFile < ApplicationRecord
# this is where users upload files to
belongs_to :user
has_many :shop_product_print_files
end
数组的形式(我选择要复选框更新的记录):
<%= form_tag edit_multiple_shop_products_path, method: :put do %>
<% @shop_products.each do |shop_product| %>
<%= hidden_field_tag "shop_product_ids[]", shop_product.id %>
<%= shop_product.id %>
<% end %>
<%= fields_for :shop_product do |f| %>
<%= f.fields_for :shop_product_print_files do |ff| %>
<%= ff.object.print_location.title %>
<%= ff.hidden_field :print_location_id %>
<%= ff.select :image_file_id, options_for_select(@image_files.map { |image| [image.id, {'data-img-src'=>image.image_file_url(:thumb)}]}), {:include_blank => 'Choose None'}, class: "image-picker" %>
Upload: <%= link_to "Add Image", user_files_path %>
<% end %>
<% end %>
<%= submit_tag "Edit Checked" %>
<% end %>
控制器:
def edit_multiple
@image_files = ImageFile.where(user_id: current_user.id)
@shop_products = ShopProduct.find(params[:shop_product_ids])
end
def update_multiple
@shop_products = ShopProduct.find(params[:shop_product_ids])
@image_files = ImageFile.where(user_id: current_user.id)
@shop_products.reject! do |shop_product|
shop_product.update_attributes(params[:shop_product].reject { |k,v| v.blank? })
end
if @shop_products.empty?
redirect_to shop_products_url
else
@shop_product = ShopProduct.new(params[:shop_product])
render "edit_multiple"
end
end
我尝试使用:
<% PrintLocation.all.each{|p| shop_product.shop_product_print_files.build(print_location: p) if shop_product.shop_product_print_files.where(print_location: p).empty? } %>
但是,我仍然收到错误消息:
(undefined method `print_location' for nil:NilClass)
这在使用form_for一次更新1条记录时有效。
我在做错什么而无法使用数组? 如何使print_locations成功显示?
此外,为了澄清,这是在创建ShopProduct之后发生的。因此,这基本上是更新现有的ShopProducts。哪个让我感到困惑,因为如果它存在,则该关联应该已经存在,但不知何故?