select(value = public

Works in two unique ways.

First: takes a block so it can be used just like Array#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.

>>[: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:

=> ActiveModel::MissingAttributeError: missing attribute: other_field
Show source
Register or log in to add new notes.
November 24, 2014
1 thank

Arguments for .select must be array, :other_field, :and_one_more) has a typo. It must take an array of arguments as the description states:[:field, :other_field, :and_one_more])

January 5, 2015
1 thank

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.

December 20, 2017
0 thanks

Counting with select

If you try to write'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'field_one', 'field_two AS something').count(:all)