批量为Rails 4中的一个Model创建记录

时间:2013-08-19 16:03:56

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

我有看法:

<%= form_tag mined_materials_url do %>
  <%= render 'import_fields' %><br />
  <%= render 'import_fields' %>
  <%= button_tag :submit %>  
<% end %>

_import_fields.html.erb:

<%= text_field_tag 'mined_material[][character_id]','' %>
<%= text_field_tag 'mined_material[][material_id]','' %>
<%= text_field_tag 'mined_material[][quantity]','' %>
<%= text_field_tag 'mined_material[][price]','' %>

(我将通过JS添加更多字段)

并且需要一次将多个记录插入到同一个模型中,但由于错误而无法保存:数组的未定义方法`permit':0x00000001f63230

PARAMS:

{"utf8"=>"✓",
"authenticity_token"=>"fFR3nWwz2Q0ivED6XXyj4ICRBtj5Rdois4N++cNnCko=",
"mined_material"=>[{"character_id"=>"1",
"material_id"=>"1",
"quantity"=>"1",
"price"=>"1"},
{"character_id"=>"2",
"material_id"=>"2",
"quantity"=>"2",
"price"=>"2"}],
"button"=>""}

我怎么能允许批量创作?

修改 MinedMaterialsController

class MinedMaterialsController < ApplicationController
 before_action :set_mined_material, only: [:show, :edit, :update, :destroy]
 before_action :load_mined_material, only: :create
 load_and_authorize_resource


# GET /mined_materials/new
def new
  @mined_material = MinedMaterial.new
end

# POST /mined_materials
def create
  @mined_material = MinedMaterial.new(mined_material_params)

  respond_to do |format|
    if @mined_material.save
      format.html { redirect_to new_mined_material_path, notice: 'Mined material was successfully created.' }
    else
      format.html { render action: 'new' }
    end
  end
end

def import
end

private
# Use callbacks to share common setup or constraints between actions.
def set_mined_material
  @mined_material = MinedMaterial.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def mined_material_params
  params.require(:mined_material).permit(:character_id, :material_id, :quantity, :price, :paid_out, :date, :corp_tax)
end

def load_mined_material
  @mined_material = MinedMaterial.new(mined_material_params)
end

end

1 个答案:

答案 0 :(得分:0)

您可以将mined_material_params方法更改为:

    params.permit({mined_material: [:character_id, :material_id, :quantity, :price, :paid_out, :date, :corp_tax]} ).require(:mined_material)

permit方法仅在值为哈希时才起作用。