Alex Rivera | Logout

How to select only specific attributes from a model?

Asked 2009-08-06T08:17:09.377
10

I want to select only specific attributes from a model(id,name).

The SQL-command can be for example:

SELECT id,name,username FROM Users

Do you know how I can handle this?

Edit
Report

1 Answer

11

There's a :select option on find methods. This allows you to do:

User.find(:all, :select => 'id, name, username')

The returned objects will be User instances with those attributes available.

Or if you really want just the values without wrapping them us as User instances. You can add a method to User to return them.

def self.get_ids_and_names
  self.connection.select_all("select id, name, username from users")
end

which will return an array of hashes mapping column name to the value for that row. E.g. [{'id' => 1, 'name' => 'user1', 'username' => 'username1'}, ... ]

answered 2009-08-06T08:27:23.600

Your Answer