BC00
BC00

Reputation: 1639

Active Record Query Collecting 2 attributes

Whats the best way to query/collect 2 or 3 attributes per object when using rails/active record?

An example would be if I wanted to query my user table and grab all of the user ids and emails for a certain type of user.

If I only wanted to get the user ids I would do

User.where(:condition => nil).collect {|u| u.id}

but what if I want the id and email?

Upvotes: 1

Views: 108

Answers (1)

PinnyM
PinnyM

Reputation: 35533

Just collect the id and email in an array:

User.where(:condition => nil).collect {|u| [u.id, u.email]}

Or if you wanted a hash in the form {:id => :email}:

User.where(:conditions => nil).inject({}) {|m, u| m[u.id] = u.email; m} 

You can make this slightly more efficient if you tell the database to only get the fields that you will be needing by using select:

User.where(:conditions => nil).select([:id, :email]).
     collect {|u| [u.id, u.email]}

Upvotes: 1

Related Questions