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?

9 Answers 9

27

Pretty old question, but the rails 3 way would be:

User.pluck(:id)
Sign up to request clarification or add additional context in comments.

Comments

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'}, ... ]

1 Comment

In Rails 3: User.select("id,name,username")
3

You can also do

User.find(:all).map(&:id)

to get a list of the user ids if you are trying to get a list of user's ids or names

3 Comments

I had been googling for this for a while. Thanks!
I dont recommend it this way. Very slow
This is an answer, but its fairly slow. User.find(:all) returns a complete collection of ActiveRecord objects for each item. then with ruby it maps over those objects and returns just the IDs. You've still got that collection waiting to be garbage collected. hopefully your IDs aren't being used for other memory intensive actions. User.pluck and User.select are more efficient
2

We can use select for symbol or string such as:

User.select("id, name, username")

or

User.select(:id, :name, :username)

Comments

2

You can also pass in an array, like so:

Model.all.select ['id', 'title']

Comments

0

In mongoid, that would be:

User.only(:name, :username).where(id: params[:id]).first

Comments

0

SQL

SELECT id,name,username FROM Users

RUBY

User.select(:id, :name, :username)

with condition, you can write like: User.select(:id, :name, :username).find_by(:age 22)

Comments

0

actually for you only need write this

@user= User.select(:attributeN, :attributeN......., attributeN)
respond_to do |format|
  format.json {
    render json: @user
  }

Comments

0

Just for those looking to get a single field

Client.select(:id) #The ids on an Active::Record collection Client.select(:id).pluck(:id) #the ids on an Array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.