问题
I've been bumbling my way through tutorials/forums in an attempt to figure out how update multiple methods using checkboxes.
I need to be able to list my "events" and check or uncheck them if the date is available. I'd like to do this on one form. I know this is possible, but I'm finally coming here after failing to get it working.
With the code I've posted I'm getting "Wrong Number of Arguments, 2 for 1" error.
I've tried these info sources: http://railscasts.com/episodes/52-update-through-checkboxes http://discuss.codeschool.io/t/surviving-apis-with-rails-posting-multiple-records/4776/4 http://railscasts.com/episodes/165-edit-multiple-revised
Here's where I'm at
routes.rb
resources :events do
collection do
put :verified
post :make_events
end
end
events_controller.rb
def verified
if Event.update_all(["available", true], :id => params[:event_ids])
redirect_to step2_path(:pid => @project.id, :u => current_user.id)
else
end
end
show.html.erb
<%= form_tag verified_events_path(:pid => @project.id ), method: :put do %>
<table class="table-event-dates">
<thead>
<tr>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody>
<tr><% @these_events.each do |event| %>
<td><%= check_box_tag "event_id[]", event.id, :value => event.available %></td>
<td><label> <%= event.date.strftime("%A, %b. %d %G") %></label></td>
</tr>
</tbody>
<% end %>
</table>
</div><br><!-- panel-body -->
<div class="panel-footer2">
<div class="row">
<%= submit_tag 'Verify Dates', :class => 'btn btn-green btn-lg btn-block' %>
<% end %>
回答1:
Probably it should work in old-fashioned style:
Event.update_all("available = 1", ["id in (?)", params[:event_ids]])
perhaps available = true
or 'true'
, i'm not sure. Or:
Event.update_all(["available", true], ["id in (?)", params[:event_ids]])
However, maybe you should clear params. Check that they are in correct form (1, 2, 4
..).
Also you could try this:
Event.where(id: params[:event_ids]).update_all(available: true)
回答2:
This question has been stale for a while but for what it's worth, the other error in the code provided that NothingToSeeHere mentions in the comment is:
In the view you have singular event_id
<%= check_box_tag "event_id[]", event.id, :value => event.available %>
In the controller you have plural event_ids
Event.update_all(["available", true], :id => params[:event_ids])
Both the params need to match and be plural. Zishe's last example for how to handle the update on the controller side is the convention for Rails 4.
<%= check_box_tag "event_ids[]", event.id, :value => event.available %>
Event.where( :id => params[:event_ids] ).update_all( :available => true )
来源:https://stackoverflow.com/questions/25309225/update-multiple-records-in-one-form-using-checkboxes-wrong-number-of-arguments