How to update multiple records' attributes from check boxes in Rails 3?
I have an attribute to add a page to my site's navigation (its a boolean) and I want to be able to turn pages on and off from check boxes all at once. I tried following this railscast: http://railscasts.com/episodes/52-update-through-checkboxes but Im running into two problems.
One - I want the check boxes to show the current state of the "navbar" option.
and two - Im not sure how to update the navbar field.
Here is my controller:
def nav
Section.update_all([:navbar => :params[:navbar]], :id =>params[:section_ids])
flash[:success] = "Sections were added to navbar"
redirect_to(admin_sections_path)
end
and my view:
<%= form_tag nav_admin_sections_path, :method => :put do %>
<ol id="section_list" class="records_list">
<% @sections.each do |section| %>
<li id="section_<%= section.id %>">
<table>
<tr class="handle">
<td class="title link_icon directory_link"><%= section.name %></td>
<td 开发者_运维技巧class="option"><%= check_box_tag "section_ids[]", section.id %></td>
<td class="action"><%= link_to 'Edit', edit_admin_section_path(section), :class=>"link_icon edit_link" %></td>
<td class="action">
<% if section.has_bio == false %>
<%= link_to 'Destroy', admin_section_path(section), :confirm => 'Are you sure?', :method => :delete, :class=>"link_icon delete_link" %>
<% end %>
</td>
</tr>
</table>
</li>
<% end %>
</ol>
<ol>
<li class="submit">
<%= submit_tag %>
</li>
</ol>
<% end %>
The table is nested in the list item because of some jquery-ui sortable stuff Im doing.
Anyway I need that check box to show the current state of :navbar AND I need to be able to update them. Right now if I try to update them I get this error:
can't convert Symbol into Integer
app/controllers/admin/sections_controller.rb:95:in `[]'
app/controllers/admin/sections_controller.rb:95:in `nav'
on this line in my controller"
Section.update_all([:navbar => :params[:navbar]], :id =>params[:section_ids])
So I guess Im not passing the check_box state into my controller correctly.
Have the checkbox check properly. Just add the boolean as the third argument.
<td class="option"><%= check_box_tag "section_ids[]", section.id, section.navbar %></td>
update the navbar field You'll have to set both the sections where navbar is on and off.
ids = [*params[:section_ids]] + [0] # makes sure it works when no navbars are selected Section.update_all({:navbar => true}, {:id => ids}) Section.update_all({:navbar => false}, "sections.id NOT IN (#{ ids.join(',') })")
EDIT
Needs double quotes instead of single quotes in second update_all. Updated the above code.
EDIT 2
Enclosing the comma inside the join
in quotes
精彩评论