How to update a list of Models 'automatically' in 1 action

If I have a User table and a form that displays all my users with a
Rank. I want to be able to rank my users and then hit ‘update’ and all
users will be parsed by my action into User model obects and then
persisted with their new rank to the DB.

Using “scaffold :user” in my controller works wonders for Single
instance CRUD functionality of my User class, but can it be done with a
list?

So basically I have this

def get_users
@user_list = User.find_all()
end

In my views I’m doing.
<% form_tag :action => ‘update_users’ do %>
<% for user in @user_list %>
<%-- display the user information here as a form -->
<% end %>
<% end %>
<%= submit_tag “Update Users” %>

I would love to have the submit button (and associated action call)
update ALL the users automatically without ME having to create a complex
parser to break all the :params being passed into User objects and save
them 1 by 1. (Through a loop of course).

I hope my description is clear… it’s crystal in my head. :wink:

I am still relatively new to Rails so I am not sure if there is an
automated way to do this, but if there isn’t, why would it be complex?
This should work and isn’t too complex…

In Controller:
def update_users
@user_list = User.find(params[:user].keys)
for user in @user_list
user.rank = params[:user][user.id][:rank]
user.save
end
end

In View:
<% for @user in @user_list %>
<%= text_field ‘user[]’, ‘rank’ %>
<% end %>

In Controller:
def update_users
@user_list = User.find(params[:user].keys)
for user in @user_list
user.rank = params[:user][user.id][:rank]
user.save
end
end

In View:
<% for @user in @user_list %>
<%= text_field ‘user[]’, ‘rank’ %>
<% end %>

I hate to reply to my own post, but I just found a way to do it with one
line. The view code I wrote above is still applicable, but in the
controller you can put:

User.update(params[:user].keys, params[:user].values)

I found this in the book Agile Web D. with Rails, 2nd ed, p499.

There doesn’t seem to be a good way to catch errors with this method,
though.

Kip wrote:

Dondi,

Perhaps this might help (with lots of error checking)

The OP wanted to update the whole list of users as simple as possible. I
do not know if they needed error checking or not, so I wanted to point
out that the one-liner I found won’t catch errors (it returns the user
objects even if they failed validation and could not be saved).

Dondi,

Perhaps this might help (with lots of error checking)
if user = User.find(params[:user][:id]) then
if user.update_attributes(params[:user].keys,
params[:user].values) then
if user.save then
puts “All updated OK”
redirect or something
else
puts “Save failed”
end
else
puts “Validation failed”
end
else
puts "Couldn’t find the user in the database
end
render

Cheers, --Kip

On Aug 2, 9:27 am, Dondi S. [email protected]