为动态键配置强参数 [英] Configuring strong parameters for dynamic keys
问题描述
我正在尝试提供一种表格,该表格允许管理员编辑特定模型Submission
的所有值,就好像它是电子表格一样. Submission
由一个字符串字段:domain
组成.
I'm attempting to provide a form that allows an admin to edit all values of a particular model Submission
, almost as though it was a spreadsheet. Submission
is comprised of one string field :domain
.
问题是,我无法弄清楚在这种情况下如何处理强大的参数.我已经找到了类似的例子来处理动态键,例如这一个,但我不太清楚如何应用它们.我的参数结构.我想我对tap
的工作方式还不够清楚.
The problem is that I can't figure out how to deal with strong params within this context. I've found similar examples of dealing with dynamic keys like this one but I can't quite figure out how to apply them to my parameter structure. I think I'm just not clear enough on how tap
works.
这是我的参数示例:
{"3"=>{"domain"=>"domain3"}, "2"=>{"domain"=>"domain2"}, "1"=>{"domain"=>"domain1"}
如果有帮助,这是我正在使用的表格:
In case it helps, here's the form I'm using:
<%= form_tag update_multiple_submissions_path, method: :put do %>
<table data-toggle="table" data-sort-name = "domain" data-sort-order = "desc">
<thead>
<th data-field="domain" data-sortable="true">Domain</th>
</thead>
<tbody>
<% @submissions.each do |submission| %>
<%= simple_fields_for "submissions[]", submission, defaults: {label: false} do |f| %>
<tr>
<td><%= submission.domain %><%= f.input :domain %></td>
</tr>
<% end %>
<% end %>
</tbody>
<table>
<%= submit_tag "Save" %>
<% end %>
如果您好奇的话,这是我控制器中的update_multiple
方法.如果看起来很熟悉,我会从railscast获得轮廓,该轮廓在rails3中非常有效,然后(无处不在)强大的参数普遍存在.
And in case you're curious, here's the update_multiple
method from my controller. If this looks familiar, I got the outline from a railscast, which was very effective in rails3 before strong params was (were?) ubiquitous.
def update_multiple
logger.debug "update_multiple #{submission_params}"
@submissions = Submission.update(submission_params[:submissions].keys, params[:submissions].values)
flash[:notice] = "Updated Submissions"
redirect_to review_submissions_path
end
如果我完全使用params.permit!
绕过强壮的婴儿车,这将非常有效,但是,当然,这是不可接受的解决方案.
This works very well if I bypass strong prams altogether using params.permit!
but, of course, this is an unacceptable solution.
感谢您的帮助!
推荐答案
您可以使用虚拟"模型(没有表的模型):
You can use a "virtual" model (a model without a table):
class SubmissionFormCollection
include ActiveModel::Model
attr_accessor :submissions
end
def edit_multiple
@collection = SubmissionFormCollection.new(
Submission.all
)
end
<% simple_form_for(@collection, as: :some_param_key, path: update_multiple_submissions_path, method: :put) do |f| %>
<%= f.fields_for(:submissions) do |s| %>
<%= s.input :domain %></td>
<% end %>
<% end %>
params.require(:some_param_key)
.permit(submissions: [:domain])
尽管我可能会使用ajax并将其作为一系列原子性的PATCH请求,而不是针对每个已编辑的项目执行,因为它会提供直接的用户反馈和更好的API.
Although I would probably use ajax and perform it as a series of atomical PATCH requests for each item edited instead as it will give direct user feedback and a better API.
这篇关于为动态键配置强参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!