Rails (ActiveRecord): last selection overrides previous

I want to combine two choices:

Place.select('name').select('city')
# => SELECT "places"."city" FROM "places"

But he selects only the city column. I think everyone else chooses to cancel the previous one. Is it possible to combine many samples?

The above code is a simple example based on my real problem. Solutions such as putting everything to one choice:

Place.select('name, city)

... are useless to me because I join him many times.

Thanks in advance!

+4
source share
1 answer

With arel

Arel may be useful to achieve your goal ...

p = Place.arel_table
arel_select = p.project('name').project('city')

arel_select.to_sql
=> "SELECT name, city FROM \"places\"" 

Place.find_by_sql(arel_select.to_sql)

Also works

arel_select = p.project('name')
arel_select.project('city').to_sql

But keep in mind ...

arel_select = p.project('name').project('city').project('city')

arel_select.to_sql
=> "SELECT name, city, city FROM \"places\"" 

With ActiveRecord

The merge method can also combine selected parts.

Place.select(:name).merge( Place.select(:city) )

SQL

SELECT "places"."name", "places"."city" FROM "places"

:

=> #<ActiveRecord::Relation [#<Place id: nil, name: "Zoo", city: "Berlin">]> 

,

Place.select(:name).merge( Place.select(:city) ).merge(Place.select(:city) )

, ,

Eugen

+1

Source: https://habr.com/ru/post/1622627/


All Articles