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

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

问题描述

我有模型简介.个人资料 has_one 用户.用户模型具有字段电子邮件.当我打电话

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

Profile.some_scope.includes(:user)

它调用

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

但是我的用户模型有很多我没有在渲染中使用的字段.是否可以只加载来自用户的电子邮件?所以,SQL 应该看起来像

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 无法为 include 查询传递选项.但是我们可以通过模型下的关联声明来传递这些参数.

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

对于您的场景,您需要在配置文件模型下创建与用户模型的新关联,如下所示

For your 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"

我刚刚又创建了一个关联,但它仅指向用户模型.所以你的查询将是,

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

Profile.includes(:user_only_fetch_email)

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

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

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