Saving a collection


#1

Reading the Agile book, I can’t find a single command to save a
collection.
The save command seems to operate on only individual objects.

Lets say I have a collection that I have received from a find_all
command.
I want to go through and change some attributes in various objects in
the
collection. Then I want to resave the whole collection back to the
database. I don’t think the update_all command is right for this, as it
understand it…

Do I just have to iterate through the collection, issuing a save command
on
each object?

Thanks for any advice…

Shelby


#2

On 12/31/05, Shelby W. removed_email_address@domain.invalid wrote:

each object?

To the best of my knowledge, there’s not a quicker way than:
@your_collection.each {|r| r.save}

On the other hand, you probably also need to make sure the records are
valid, so…
good_to_go = true
@collection.each do |record|
good_to_go = false unless record.save
end
flash[:notice] = “All records saved. Lunch break!” if good_to_go
etc, etc, etc.

I have a lot of this stuff in my Rails apps, so hopefully someone will
come along with a better way.


#3

Do I just have to iterate through the collection, issuing a save command
on

each object?

To the best of my knowledge, there’s not a quicker way than:
@your_collection.each {|r| r.save}

Thanks, Wilson - I couldn’t figure out any other way to do it as
well…

Shelby


#4

On the other hand, you probably also need to make sure the records are
valid, so…
good_to_go = true
@collection.each do |record|
good_to_go = false unless record.save
end
flash[:notice] = “All records saved. Lunch break!” if good_to_go
etc, etc, etc.

You could also do it like this:

good_to_go = @collection.all? { |r| r.save }

Dan


#5

On 1/1/06, Dan K. removed_email_address@domain.invalid wrote:

good_to_go = @collection.all? { |r| r.save }

Nice one. The best posts on this list are the ones that make me feel
stupid.
I’m going to rewrite some actions now. :slight_smile: