Update multiple records in the same table

Hey,

Sorry to ask this, but I’m really confused!

I have an app to handle guest lists. When a user wants to edit a list, I
create a one form with fields for each guest to make it easier to update
all in one go. Like this…

Guest 1 | [name] [company] [email]

Guest 2 | [name] [company] [email]

Guest 3 | [name] [company] [email]

SUBMIT

How do I update them all with one form submission?

Thanks

Hi Scott,

I’m going to haml here because rhtml sucks hard to code:

edit_multiple.haml:
= form_tag :controller => ‘guests’, :action => ‘update_multiple’
%table
= render :partial => ‘form’, :collection => @guests

_form.haml:
%tr
%td= input_tag “guest[#{guest.id}][name]”, guest.name
%td= input_tag “guest[#{guest.id}][company]”, guest.company

guests_controller.rb:
class GuestsController < ApplicationController

RESTful routes or:

verify :method => :post, :params => :guest, :only => :update_multiple

def update_multiple
guest_ids = params[:guest].keys

# better off by placing this in the model...
Guest.transaction do
  guest_ids.each { |guest_id| Guest.update guest_id, 

params[guest_id] }
end
end

end

Untested!

Regards
Florian

Hey,

Thanks for that. I found this code which seems to work:

def update_guestlist

@params[:guest].each do |g, guest|
guest_line = Guest.find(g)
guest_line.update_attributes(guest)
end

redirect_to :controller => ‘groups’

end

But is there anyway of ensuring that all of the data has been saved
before redirecting?

Thanks!

Ps - Thanks for the HAML tip. I have never heard of it but it seems to
take a lot of the work out of coding the view!

Scott H. wrote:

But is there anyway of ensuring that all of the data has been saved
before redirecting?

You will want to look into transactions. Since the rails wiki is down,
here is the cached Google page.

http://64.233.167.104/search?q=cache:rGXAaODr8moJ:wiki.rubyonrails.org/rails/show/HowToUseTransactions+rails+transactions&hl=en&ct=clnk&cd=1&gl=au

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs