method

select

select(value = Proc.new)
public

No documentation available.

# File activerecord/lib/active_record/relation/query_methods.rb, line 40
    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

3Notes

Arguments for .select must be array

kmok · Nov 24, 20141 thank

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

lazylester · Jan 5, 20151 thank

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

jmarceli · Dec 20, 2017

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)