问题
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
.
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.
Here's an example of my parameters:
{"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 %>
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
This works very well if I bypass strong prams altogether using params.permit!
but, of course, this is an unacceptable solution.
Thanks for any help!
回答1:
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])
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.
来源:https://stackoverflow.com/questions/41207766/configuring-strong-parameters-for-dynamic-keys