v4.0.2 - Show latest stable - 0 notes - Class: ActiveRecord::QueryMethods
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 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">]

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 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 will throw ActiveModel::MissingAttributeError:

# => ActiveModel::MissingAttributeError: missing attribute: other_field
Show source
Register or log in to add new notes.