是否有可能要求只有某些列从一个ActiveRecord的关联? [英] Is it possible to ask for only certain columns from an ActiveRecord association?

查看:114
本文介绍了是否有可能要求只有某些列从一个ActiveRecord的关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑

 高清富
  HAS_ONE:用户
结束
 

比方说,我只想要一个用户的名字,而不是任何其他列的。所以我想

 从用户WHERE价格,ID= 123选取名称
 

但这样做 foo.user.name 会给我

  SELECT * FROM用户WHERE价格,ID= 123
 

有没有什么华而不实的方式使用该协会只得到一列?如果没有,那么我必须做的:

  User.where(ID:foo.user_id).pluck(:名称)。首先
 

解决方案

在一般的,你可以指定要选择使用。选择方法,比如哪些列:

  User.select(:名称)。凡(...)
 

这会从名字列仅返回值。你可以连上这个关联,但不是到一个实例。因此,作为meagar非常agressively指出downvoting其他答案(包括森的已删除的答案),在 HAS_ONE 的关系,你不能链这对联想(因为它不是在这种情况下,关联)。但是,你可以建立一个自定义的范围,是这样的:

 类Foo<的ActiveRecord :: Base的
  HAS_ONE:酒吧
  适用范围:bar_name,拉姆达{Bar.select(:名称)。凡(:foo_id => ID)}
结束
 

以上是未经检验的,所以你可能需要调整,但总体上说这种做法将允许你这样做是这样的:

  foo.bar_name
 

...没有从酒吧加载的所有列。

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

解决方案

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.

这篇关于是否有可能要求只有某些列从一个ActiveRecord的关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆