Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Load just one attribute not a whole model

Lets say I have a model, Foo, which is big and has lots of components. For a given Ajax query I'm only interested in one particular attribute, bar, which is a column in the foos table.

Is there a simple way I could load just that attribute, and not bother with retrieving the rest of the record? For instance if all I want to know is the bar for Foo with id#__, how could I retrieve that?

like image 265
Andrew Avatar asked May 25 '11 03:05

Andrew


4 Answers

You can return only specific columns by calling the select method with a string containing the attributes you want to return. For your example:

Foo.select('bar').first    #<Foo bar: 1>

Keep in mind that these objects will act like normal ActiveRecord objects but return nil for any field you did not select, so take care using this functionality.

You can call select on the class name itself or any Relation, so you can chain together the ActiveRecord calls you usually use like where, etc.

like image 116
Ryan Brunner Avatar answered Nov 21 '22 00:11

Ryan Brunner


I prefer this

User.where(:id => user_id).pluck(:user_name).first #'tom'
Foo.where(:age => 23).pluck(:user_name) #['tom', 'jerry', ...]
like image 33
Himanshu Patel Avatar answered Nov 20 '22 23:11

Himanshu Patel


Foo.where(<condition>).select('fieldname')

Example

results = Foo.where('is_active = ?', true).select('bar')

Access the selected fields as:

results.map {|res| res.bar} returns an array of bar's

like image 20
amit_saxena Avatar answered Nov 20 '22 23:11

amit_saxena


pluck(*column_names)

doc: http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck

e.g. Foo.pluck(:bar)

like image 36
Lukas Svoboda Avatar answered Nov 20 '22 22:11

Lukas Svoboda