select
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0 (0)
- 3.0.9 (0)
- 3.1.0 (0)
- 3.2.1 (38)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (11)
- 4.1.8 (0)
- 4.2.1 (1)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (11)
- 7.1.3.4 (0)
- What's this?
select(*fields)
public
Works in two unique ways.
First: takes a block so it can be used just like Array#select.
Model.all.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 id: nil, 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 id: nil, field: "value", other_field: "value", and_one_more: "value">]
You can also use one or more strings, which will be used unchanged as SELECT fields.
Model.select('field AS field_one', 'other_field AS field_two') # => [#<Model id: nil, field: "value", other_field: "value">]
If an alias was specified, it will be accessible from the resulting objects:
Model.select('field AS field_one').first.field_one # => "value"
Accessing attributes of an object that do not have fields retrieved by a select except id will throw ActiveModel::MissingAttributeError:
Model.select(:field).first.other_field # => ActiveModel::MissingAttributeError: missing attribute: other_field
Arguments for .select must be array
Model.select(:field, :other_field, :and_one_more) has a typo. It must take an array of arguments as the description states:
Model.select([:field, :other_field, :and_one_more])
arguments do not need to be an array
it’s a small point, but if you look at the source, the method is defined with the splat operator in the arguments:
def select (*fields)
this means that a list of arguments is automatically converted to an array. There is no typo in the description above.
It will also work to pass an array:
select([:field1, :field2])
although the select method interprets this as a single argument, and places it into an array (due to the splat operator), this is then passed to the _select(*fields) method, which immediately calls fields.flatten!
So either a list or an array may be passed, both will work.
Counting with select
If you try to write
Model.select('field_one', 'field_two AS something').count
it will fail (at least for Rails 5.0) with the message PG::SyntaxError: ERROR: syntax error at or near “AS”. In order to fix that issue, you should write
Model.select('field_one', 'field_two AS something').count(:all)