mza (owner)

Fork Of

Revisions

gist: 50076 Download_button fork
public
Public Clone URL: git://gist.github.com/50076.git
Embed All Files: show embed
index.html.haml #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
## /users/index
 
#bulk-update-form
  - for user in @users
    - fields_for "user[]", user do |f|
      = f.label :tryout
      =radio_button("user", "status", "tryout")
      
      = f.label :inactive
      =radio_button("user", "status", "inactive")
      
      = f.label :active
      =radio_button("user", "status", "active")
  
  = link_to_remote '[save]', :url => {:action => 'update' }, :submit => "bulk-update-form", :method => 'put'
  
 
 
Update multiple records of a single model simultaneously #
1
2
3
4
5
6
7
## READ ME
 
I have a user model (restful_authentication) and would like a manager to be able to update the status of his users all at once. The users have three different statuses: active, inactive, guest. Guest is the default.
 
Using radio buttons I would like the manager to have free reign over how many users update at any one time.
 
There is a way to do this using loops, but that can get expensive quickly so I am looking for a better method.
users_controller.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# You can probably do the filtering with a select on your incoming parameters
# and then use update_all to perform the update in one hit.
#
# Probably best toncapsulate the update_all into the User model to keep the
# controller clean.
#
# This code hasn't been tested!
 
def update
  @users = User.find(:all)
 
  guests = ids_from params, "guest"
  active = ids_from params, "active"
  inactive = ids_from params, "inactive"
  User.update_all "guest = true", "id IN (#{guests.join(",")}("
  User.update_all "active = true", "id IN (#{active.join(",")}("
  User.update_all "inactive = true", "id IN (#{inactive.join(",")}("
 
  respond_to do |format|
    flash[:notice] = 'Users Updated'
    format.html do
      render :update do |page|
        #reload the page or the changes won't appear
        page.reload
      end
    end
    format.xml { head :ok }
  end
 
end
 
private
 
def ids_from(parameters, key)
  parameters["user"].keys.select { |id| params["user"][id][key] == "1" }
end