I do not want to say that the following options are necessarily better than what Benj and Old Pro suggest, but rather want to provide some more alternatives.
The first one makes use of the includes
method as that is what OP asked for. But as includes
will by default select all columns of the primary model (User
), one first has to remove that default selection via the except method:
User.includes(:ocr).except(:select).select(:id, 'ocr.small_value_only')
Of course, using join
in the first place would be easier.
The following options stem from my dislike for having strings in AR queries as it tends to rely on knowledge about the called model which AR should actually abstract for you, i.e. the name of the database table (ocr
).
A naive implementation for removing that knowledge is to get the table name from the model:
User.joins(:ocr).select(:email, "`#{Ocr.table_name}`.`small_value_only`")
The next alternative relies on merge to get rid of the string for selecting the column:
User.joins(:ocr).merge(Ocr.select(:project_id)).select(:id)
But as the resulting sql does not reference the Ocr table for small_value_only
, it would be equivalent to writing:
User.joins(:ocr).select(:email, :small_value_only)
and will only work as long as small_value_only
does not also exist on the users
table.
The last alternative does not have that shortcoming but is way more verbose:
User.joins(:ocr).select(Ocr.select(:small_value_only).arel.projections).select(:id)