简体   繁体   English

Rails强参数-哈希数组-单一形式的多个记录

[英]Rails Strong Parameters - Array of Hashes - Multiple Records in Single Form

I'm trying to submit multiple records in a single form in a rail 5.2 app. 我正在尝试在Rail 5.2应用程序中以单一形式提交多个记录。 I'm not using accepts nested attributes of another model, as it always seemed to bring in the entries that were previously created. 我没有使用其他模型的嵌套属性,因为它似乎总是引入以前创建的条目。 The entries can't be edited once created. 条目一旦创建就无法编辑。

<%= form_tag entry_details_path do %>
  <% @entries.each do |entry| %>
    <%= fields_for 'entries[]', entry do |e| %>
      <div class="field">
        <%= e.label :user_account_id %><br>
        <%= e.text_field :user_account_id %>
      </div>
      <div class="field">
        <%= e.label :amount %><br>
        <%= e.text_field :amount %>
      </div>
     <% end %>
   <% end %>
   <div class="actions">
     <%= submit_tag %>
   </div>
 <% end %>

The params looks like: 参数看起来像:

"entries"=>[<ActionController::Parameters {"user_account_id"=>"3", "amount"=>"55"} permitted: false>, <ActionController::Parameters {"user_account_id"=>"4", "amount"=>"65"} permitted: false>]

I want to pash the entire array of hashes to a create such as: 我想将整个散列数组伪装成一个创建物,例如:

def create_multiple_entries
  @entries = Entries.create(multiple_entries_params)
  @entries.reject! { |e| e.errors.empty? }
  if @entries.empty?
    redirect_to entries_path
  else
   render 'new'
 end
end

The method above works if manually enter an array. 如果手动输入数组,则上述方法有效。 My challenge is the strong parameters(I think). 我的挑战是强大的参数(我认为)。 Right now I have: 现在我有:

def leave_accrual_details_params
  params.require(:entries).permit([:user_account_id, :amount])
end

Which gives me the following error: 这给了我以下错误:

!! #<NoMethodError: undefined method `permit' for #<Array:0x00007fee4014ec78>>

Try the following for Rails 5: 对于Rails 5,请尝试以下操作:

def leave_accrual_details_params
  params.require(:entries).map do |p|
    p.permit(:user_account_id, :amount)
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM