Is it possible to ask for only certain columns from an ActiveRecord association?
activerecord, associations, ruby, ruby-on-rails
Solution
In general you can specify what columns you want to select using the .select method, like:
User.select(:name).where(...)
This will return just the values from the name column. You can chain this onto an association, but not onto an instance. So, as meagar very agressively pointed out by downvoting the other answers (including Mori's deleted answer), in a `has_one` relationship you can't chain this on the association (because it's not an association in that case). However, you could build a custom scope, like this:
class Foo < ActiveRecord::Base
has_one :bar
scope :bar_name, lambda {Bar.select(:name).where(:foo_id=> id)}
end
The above is untested so you may have to tweak it, but generally speaking that approach would allow you to do something like:
foo.bar_name
...without loading all the columns from Bar.
Problem
consider ``` def Foo has_one :user end ``` let's say i only want a `Foo`'s `User`'s name, and not any of the other columns. so i want ``` SELECT name FROM "users" WHERE "prices"."id" = 123 ``` but doing `foo.user.name` will give me ``` SELECT * FROM "users" WHERE "prices"."id" = 123 ``` is there any slick 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 ```