ActiveRecord Question -- making arrays or hashs out of database tables

Thanks for your reply. This is very helpful.
Glenn

···

----- Original Message ----
From: Daniel Bush <dlb.id.au@gmail.com>
To: ruby-talk ML <ruby-talk@ruby-lang.org>
Sent: Wednesday, August 20, 2008 2:55:07 PM
Subject: Re: ActiveRecord Question -- making arrays or hashs out of database tables

Glenn wrote:

Better yet, I'd like to be able to create an array of hashes, where each
element of the array is equal to a hash of the fields in the table, like
this:
[{:x => 1, :y => 'a', :z => 1.1}, {:x => 2, :y => 'b', :z => 6.2}, {:x
=> 3, :y => 'c', :z => 0.001}]

Yes, you can do that.
I have a 'clients' table which is represented by a 'Client' model (maybe
in a rails application).
I can do
clients=Client.find(:all).collect {|c| c.attributes }
and access it like
clients.each do |client|
client['first_name'] # do something with first_name field value
end
which gives you your array of hashes.
However,
clients=Client.find(:all)
will give you
clients.each do |client|
client.first_name
end
which is nicer and you get all the power of active record as a result,
because 'client' is an instance of Client and not just a hash.

Can anyone tell me if this is doable in ActiveRecord, or in some other
Ruby package, or with some stand-alone Ruby code?

Someone might shoot me down here, but I'd say that ActiveRecord is good
for working with small updates and selects as in the sort of thing you
might do with a web app interface.
If you're not using rails, then it is quite likely you might look at
alternatives. There are drivers for various databases which will fetch
data into arrays and hashes, and their are also alternatives to
activerecord which do ORM. Haven't been using a lot of them lately and
it may depend on the database.

Regards,
Daniel
--
Posted via http://www.ruby-forum.com/\.