Try:
params[:illness].each do |key, value| @rec = key # This will be “1” @to_update = Illness.find(@rec) @to_update.qualifier = value[:qualifier] @to_update.illness_date = value[:illness_date] @to_update.save
end
It would probably be a good idea to put all these updates in a
transaction too, so that if any fail they all fail.
No Bill, I only put it in a separate variable to match what you had done
Yeah, transactions are pretty simple, you would probably set up
something like
ActiveRecord::Base.transaction do
params[:illness].each do |key, value| @to_update = Illness.find(key) @to_update.qualifier = value[:qualifier] @to_update.illness_date = value[:illness_date] @to_update.save!
end
end
If/when the exception is thrown on save!, the transaction is rolled
back and the exception is rethrown. So, you’ll need to catch
ActiveRecord::RecordInvalid and do something intelligent. If you want
to be a bit more clever about it and show which ones have errored,
it’d be better to do this:
begin
ActiveRecord::Base.transaction do
savestatus = []
params[:illness].each do |key, value| @to_update = Illness.find(key) @to_update.qualifier = value[:qualifier] @to_update.illness_date = value[:illness_date]
savestatus << @to_update.save
end
raise Exception if savestatus.include?(false)
end
flash[:notice] = “Saved successfully”
redirect_to :action => “here” and return
rescue
flash[:notice] = “Error saving record”
end
and then you could redisplay the objects with errors. For the docs,
just go to rails.rubyonrails.com and check out the
ActiveRecord::Transactions::ClassMethods doc.
Thanks for the heads-up… I’m not getting a broken link but I’ll have
a poke about and see if there’s a problem
Thanks much for your reply. I finally found the hash documentation in
the
Programming Ruby PDF and had gotten it working with just about the exact
same code. The only difference is that I used ‘key’ in the
Illness.find()
statement rather than assigning it to a separate variable like you did.
Is
there a risk in doing it the way I did?
I’m very new to RoR and haven’t tackled transactions yet. Is the
documentation easy to find / understand?
Also, just fyi, I checked out your site and two of the image links at
the
top right are giving a page not found errors. Nice looking site,
though!
Thanks again,
Bill
----- Original Message -----
From: “Dan S.” [email protected]
To: [email protected]
Sent: 2006-03-09 6:59 PM
Subject: Re: [Rails] problem with find()
Hi Bill
Try:
params[:illness].each do |key, value| @rec = key # This will be “1” @to_update = Illness.find(@rec) @to_update.qualifier = value[:qualifier] @to_update.illness_date = value[:illness_date] @to_update.save
end
It would probably be a good idea to put all these updates in a
transaction too, so that if any fail they all fail.