Rails: Load just one attribute not a whole model
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.
I prefer this
User.where(:id => user_id).pluck(:user_name).first #'tom'Foo.where(:age => 23).pluck(:user_name) #['tom', 'jerry', ...]
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