![](/img/trans.png)
[英]Rails strong parameters - multiple types (strings, array of strings and array of hashes)
[英]Rails Strong Parameters - Array of Hashes - Multiple Records in Single Form
我正在尝试在Rail 5.2应用程序中以单一形式提交多个记录。 我没有使用其他模型的嵌套属性,因为它似乎总是引入以前创建的条目。 条目一旦创建就无法编辑。
<%= 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 %>
参数看起来像:
"entries"=>[<ActionController::Parameters {"user_account_id"=>"3", "amount"=>"55"} permitted: false>, <ActionController::Parameters {"user_account_id"=>"4", "amount"=>"65"} permitted: false>]
我想将整个散列数组伪装成一个创建物,例如:
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
如果手动输入数组,则上述方法有效。 我的挑战是强大的参数(我认为)。 现在我有:
def leave_accrual_details_params
params.require(:entries).permit([:user_account_id, :amount])
end
这给了我以下错误:
!! #<NoMethodError: undefined method `permit' for #<Array:0x00007fee4014ec78>>
对于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.