Flowdock

Good notes posted by vosechu

RSS feed
August 25, 2008 - (v1.1.6 - v2.1.0)
3 thanks

Delete collections with check box tags

Following autonomous’ directions works wonders on /edit but needs slight modifications when dealing with pagination on /index.

In a /index type listing page we can no longer assume that the list of ids coming back represents changes to all objects so we need to provide some context, that the list of object modifications in our params array is a list of modifications for some set of objects.

We can only assume subsets because pagination or filtering may reduce the set of objects we’re working on.

In our case we had a user management page which listed all users and showed whether they were activated or not. The following code is what we used to ensure that modifications to the first page of objects wouldn’t affect all the other pages.

index.rhtml

<% @users.each do |user| %>
  <%= hidden_field_tag('seen[]', user.id) -%>
  <%= check_box_tag 'activated[]', user.id -%>
<% end %>

role_controller.rb

def index
  if request.post?
    activated_ids = params[:activated].collect {|id| id.to_i} if params[:activated]
    seen_ids = params[:seen].collect {|id| id.to_i} if params[:seen]

    if activated_ids
      seen_ids.each do |id|
        r = User.find_by_id(id)
        r.activated = activated_ids.include?(id)
        r.save
      end
    end
  end
end