instance method
select
Ruby on Rails 3.2.22.5
Since v3.0.20Signature
select(value = Proc.new)
Works in two unique ways.
First: takes a block so it can be used just like Array#select.
Model.scoped.select { |m| m.field == value }
This will build an array of objects from the database for the scope, converting them into an array and iterating through them using Array#select.
Second: Modifies the SELECT statement for the query so that only certain fields are retrieved:
>> Model.select(:field) => [#<Model field:value>]
Although in the above example it looks as though this method returns an array, it actually returns a relation object and can have other query methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
The argument to the method can also be an array of fields.
>> Model.select([:field, :other_field, :and_one_more]) => [#<Model field: "value", other_field: "value", and_one_more: "value">]
Any attributes that do not have fields retrieved by a select will raise a ActiveModel::MissingAttributeError when the getter method for that attribute is used:
>> Model.select(:field).first.other_field => ActiveModel::MissingAttributeError: missing attribute: other_field
Parameters
-
valueopt = Proc.new
Source
# File activerecord/lib/active_record/relation/query_methods.rb, line 70
def select(value = Proc.new)
if block_given?
to_a.select {|*block_args| value.call(*block_args) }
else
relation = clone
relation.select_values += Array.wrap(value)
relation
end
end
Defined in activerecord/lib/active_record/relation/query_methods.rb line 70
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::QueryMethods