Forum: Ruby on Rails Manipulating collections

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7bbc5c78011f20a36ee0cffa15b575ef?d=identicon&s=25 Chris Birkinshaw (Guest)
on 2006-06-04 18:24

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
D0cd6b10e01bacb976b3b815a9c660bc?d=identicon&s=25 Alex Wayne (Guest)
on 2006-06-04 20:11
Chris Birkinshaw 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.
7bbc5c78011f20a36ee0cffa15b575ef?d=identicon&s=25 Chris Birkinshaw (Guest)
on 2006-06-04 20:48

Thanks for the reply, that has helped me enourmously.

Chris
This topic is locked and can not be replied to.