问题
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
回答1:
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.
回答2:
No, in the case of your has_one
, but yes in the case of has_many
.
The object returned for a has_one
association isn't a scope onto which you can chain additional methods like select
, like with a has_many
. It's an actual instance of the model, and instantiating it will necessarily involve a select *
.
If you want to select just the name, you'll have to access the User
model directly and use select
.
Conversely, if your Foo
has many users
, you could use foo.users.select("name")
or any of the other chainable methods, as foo.users
would be an actual ActiveRecord association, not an instance of a model.
来源:https://stackoverflow.com/questions/16111930/is-it-possible-to-ask-for-only-certain-columns-from-an-activerecord-association