问题
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?
回答1:
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.
回答2:
I prefer this
User.where(:id => user_id).pluck(:user_name).first #'tom'
Foo.where(:age => 23).pluck(:user_name) #['tom', 'jerry', ...]
回答3:
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
回答4:
pluck(*column_names)
doc: http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
e.g. Foo.pluck(:bar)
来源:https://stackoverflow.com/questions/6119167/rails-load-just-one-attribute-not-a-whole-model