Can I query only specific columns from an ActiveRecord association?

consider

def Foo has_one :user end 

let's say I only need the name Foo User and not any of the other columns. so i want

 SELECT name FROM "users" WHERE "prices"."id" = 123 

but executing foo.user.name will give me

 SELECT * FROM "users" WHERE "prices"."id" = 123 

Is there any way to use the association to get only one column? if not, then I have to do:

 User.where(id: foo.user_id).pluck(:name).first 
+6
source share
2 answers

In general, you can specify which columns you want to select using the .select method, for example:

 User.select(:name).where(...) 

This will only return values ​​from the name column. You can associate this with an association, but not with an instance. Thus, since meagar was very aggressive in pointing out that other responses were downvoting (including the Mori remote response), with regard to has_one you cannot associate this with an association (because it is not an association in this case). However, you can create a custom scope, for example:

 class Foo < ActiveRecord::Base has_one :bar scope :bar_name, lambda {Bar.select(:name).where(:foo_id=> id)} end 

The above is not verified, so you may have to fine-tune it, but overall this approach will allow you to do something like:

 foo.bar_name 

... without loading all columns from the panel.

+4
source

No, in the case of your has_one , but yes in the case of has_many .

The object returned for the has_one association is not the area to which you can associate additional methods, such as select , for example with has_many . This is an actual instance of the model, and select * will be required to create it.

If you want to select only the name, you need to directly access the User model and use select .

Conversely, if your Foo has many users , you can use foo.users.select("name") or any of the other related methods, since foo.users will be a real ActiveRecord association, not a model instance.

+1
source

All Articles