Manipulating collections


#1

I appreciate this is basic stuff but can’t seem to find the answer
anywhere using Google. If someone could point me in the direction of
some documentation on this I would be very appreciative.

If I have a collection as follows:

@stuff = Stuff.find_by_type(‘new’)

And I then want to add something onto it, how can I add to this
collection?

Additionally how could I go through the collection and say change or add
an attribute after matching certain objects?

many thanks,

Chris


#2

Chris B. wrote:

I appreciate this is basic stuff but can’t seem to find the answer
anywhere using Google. If someone could point me in the direction of
some documentation on this I would be very appreciative.

If I have a collection as follows:
@stuff = Stuff.find_by_type(‘new’)

And I then want to add something onto it, how can I add to this
collection?

ActiveRecord finders return arrays of ActiveRecord objects. So treat
them like you would any other array.

@stuff = Stuff.find_by_type(‘new’)
new_stuff = Stuff.create(:foo => ‘bar’)
@stuff << new_stuff

Additionally how could I go through the collection and say change or add
an attribute after matching certain objects?

@fitered_stuff = @stuff.find do |object| #array.find not
active_record.find
object.foo == ‘bar’
end
@filtered_stuff.each do |row|
row.update_attribute :foo, ‘baz’
end

Although you may be better off only pulling the relevant records from
the DB rather than filtering them after the fact. SQL is very good at
that sort of thing.


#3

Thanks for the reply, that has helped me enourmously.

Chris