从单个表单提交相同模型的多个对象

时间:2016-10-17 17:38:58

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5

我想从单个表单提交相同模型的多个对象(哈希数组)。我的参数只显示一个对象,即使我尝试提交多个对象。

我的参数看起来像:

serialized_products

我期待一个名为Parameters: {"utf8"=>"✓", "authenticity_token"=>"bbT3qiNZxFrO9RYLL3g==", "serialized_products"=>[{"product_id"=>"1", "location_id"=>"1", "serial"=>"2345454353454"}, {"product_id"=>"1", "location_id"=>"1", "serial"=>""}, {"product_id"=>"1", "location_id"=>"1", "serial"=>""}, {"product_id"=>"2", "location_id"=>"1", "serial"=>"454356536556"}, {"product_id"=>"2", "location_id"=>"1", "serial"=>""}], "commit"=>"Save changes"} 的params哈希中的密钥,其中包含一系列序列化产品:

undefined method 'permit' for "product_id":String Did you mean? print

提交表单时出现此错误:

<%= form_tag serialized_products_path do %> <% @serialized_products.each do |product| %> <%= fields_for 'serialized_products[]', product do |p| %> <%= p.label :product_id %><br> <%= p.text_field :product_id %> <%= p.label :location_id %><br> <%= p.text_field :location_id %> <%= p.label :serial %><br> <%= p.text_field :serial %> <% end %> <% end %> <%= submit_tag %> <% end %>

在从Rails 4.2升级到Rails 5之前,它工作正常。

我有以下代码,改编自此处:

http://vicfriedman.github.io/blog/2015/07/18/create-multiple-objects-from-single-form-in-rails/

形式:

class SerializedProductsController < ApplicationController
  before_action :set_serialized_product, only: [:show, :edit, :update, :destroy]

  def new
    if session[:reference] == nil or session[:location_id] == nil or session[:line_item_ids] == nil
      print "\n\nSession is nil.\n\n"
      redirect_back(fallback_location: root_path)
    end

    @reference = session[:reference]
    location_id = session[:location_id]
    @line_items = InventoryAdjustmentItem.where(id: session[:line_item_ids])
    @serialized_products = []
    @line_items.each do |line_item|
      (line_item.quantity).times do 
        @serialized_products.push(SerializedProduct.new(product_id: line_item.product_id, location_id: location_id))
      end
    end
  end

  def create
    params["serialized_products"].each do |serialized_product|
      if serialized_product["serial"].present?
        SerializedProduct.create(serialized_product_params(serialized_product))
      end
    end
    redirect_to :root, notice: 'Serialized product was successfully created.'
    session[:reference] = nil
    session[:location_id] = nil
    session[:line_item_ids] = nil
  end

  private
    def set_serialized_product
      @serialized_product = SerializedProduct.find(params[:id])
    end

    def serialized_product_params(my_params)
      my_params.permit(:product_id, :location_id, :serial)
    end
end

SerializedProducts Controller:

<head>

0 个答案:

没有答案