I have a site that shows upcoming events. Event
has a boolean property called :approved
. I want to display a list of all the events for an admin and checkboxes for the :approved
field. They should be checked if approved and unchecked otherwise. I'm guessing I need to use fields_for
? When the admin checks an :approved
field in the form I want it to transmit inside params as '1' or 'true' or 'checked' and the opposite when he unchecks the field and submits the form. I also need the name of each field in the params list to be something like events[event.id]
but what I have comes up as events[event.id][approved]
and none of my checkboxes are checked. Here's what I have so far:
admin_index.html.erb
<%= form_tag '/admin_events', method: :get do %>
<table id="admin_events_table" class="table-striped" style="width: 100%">
<thead>
<th>Date</th>
<th>Time</th>
<th>Title</th>
<th>Venue</th>
<th>Visibility</th>
<th></th>
<th></th>
</thead>
<tbody id="admin_events">
<%= render @events %>
</tbody>
</table>
<%= submit_tag "Approve", class: "btn btn-default" %>
<% end %>
_event.html.erb
<tr>
<td><%= fields_for "events[#{event.id}]" do |form| %>
<%= form.check_box :approved %>
<% end %>
</td>
<td><%= event.date.strftime('%A %B %-d') %></td>
<td><%= event.time.strftime('%l:%M %P') %></td>
<td><%= event.title %></td>
<td><%= Venue.find(event.venue_id).name %></td>
<td><%= link_to "Edit", edit_event_path(event) %></td>
<td><%= link_to "Delete", event, method: :delete, data: { confirm: "Are you sure?" } %></td>
UPDATE
here's what I came up with in my controller in order for the app to update :approved
to either true or false. But it seems too complicated:
events_controller.rb
if params[:commit]
ids = params[:events].keys
values = params[:events].values
ids.each_with_index do |id, i|
event = Event.find(id)
if values[i].values[0] == "0"
event.update(approved: false)
else
event.update(approved: true)
end
end
redirect_to admin_events_path
end
If your view looks like this:
<%= fields_for "events[]", event do |form| %>
<%= form.check_box :approved %>
<% end %>
then your params should contain a hash that looks like this (let's say event with id 29 is checked and event with id 23 is unchecked):
"events" => {"29" => {"approved" => "1"}, "23" => {"approved" => "0"}}
and your controller can save them like this:
events = params[:events]
events.each do |id, attrs|
event = Event.find(id)
event.update_attributes(attrs)
end
redirect_to admin_events_path