我有模型简介。个人资料 has_one 用户。用户模型具有字段电子邮件。当我打电话
Profile.some_scope.includes(:user)
它叫
SELECT users.* FROM users WHERE users.id IN (some ids)
但是我的 User 模型有很多我没有在渲染中使用的字段。是否可以只加载来自用户的电子邮件?所以,SQL 应该看起来像
SELECT users.email FROM users WHERE users.id IN (some ids)
最佳答案
Rails 没有能力传递 的选项。包括 询问。但是我们可以通过 传递这些参数协会声明模型下。
对于您的场景,您需要在配置文件模型下创建与用户模型的新关联,如下所示
belongs_to :user_only_fetch_email, :select => "users.id, users.email", :class_name => "User"
我刚刚又创建了一个关联,但它仅指向 User 模型。所以你的查询将是,
Profile.includes(:user_only_fetch_email)
或者
Profile.includes(:user_only_fetch_email).find(some_profile_ids)
关于ruby-on-rails - ActiveRecord 包括。指定包含的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12400860/