ActiveRecord的包含。指定包含的列 [英] ActiveRecord includes. Specify included columns

查看:183
本文介绍了ActiveRecord的包含。指定包含的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型资料。简介HAS_ONE用户。用户模型领域的电子邮件。当我打电话

  Profile.some_scope.includes(:用户)
 

它调用

  SELECT用户。* FROM用户WHERE users.id IN(有些IDS)
 

但我的用户模型,我没有使用渲染许多领域。是否有可能从用户仅加载邮件?因此,SQL应该像

  SELECT users.email用户的WHERE users.id IN(有些IDS)
 

解决方案

Rails的不必须通过对于包含查询选项设施。但是,我们可以通过这些PARAMS与报关协会的模式下。

有关你的情况,你需要的剖面模型下创建与用户模式的新关系,如下图所示。

  belongs_to的:user_only_fetch_email,:选择=> users.id,users.email:将class_name => 用户
 

只是我创建了一个更关联,但它仅指向用户模式。所以您查询将是,

  Profile.includes(:user_only_fetch_email)
 

  Profile.includes(:user_only_fetch_email).find(some_profile_ids)
 

I have model Profile. Profile has_one User. User model has field email. When I call

Profile.some_scope.includes(:user)

it calls

SELECT users.* FROM users WHERE users.id IN (some ids)

But my User model has many fields that I am not using in rendering. Is it possible to load only emails from users? So, SQL should look like

SELECT users.email FROM users WHERE users.id IN (some ids)

解决方案

Rails dont have the facility to pass the options for include query. But we can pass these params with the association declaration under the model.

For you scenario, you need to create a new association with users model under the profile model, like below

belongs_to :user_only_fetch_email, :select => "users.id, users.email", :class_name => "User"

just i created one more association but it points to User model only. So you query will be,

Profile.includes(:user_only_fetch_email)

or

Profile.includes(:user_only_fetch_email).find(some_profile_ids)

这篇关于ActiveRecord的包含。指定包含的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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