ActiveRecord包括.指定包含的列



我有模型配置文件。配置文件只有一个用户(_O)。用户模型有字段电子邮件。当我呼叫时

Profile.some_scope.includes(:user)

它调用

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

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

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

Rails没有传递include查询选项的功能。但是,我们可以在模型下通过关联声明来传递这些参数。

对于您的场景,您需要在概要文件模型下创建一个与用户的新关联模型,如下面的

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

我只创建了一个关联,但它只指向用户模型。所以你的问题是,

Profile.includes(:user_only_fetch_email)

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

如果要选择特定的属性,应该使用joins而不是includes

来自这个ascicast:

include选项并不能真正与select选项配合使用,因为我们无法控制select语句的第一部分是如何生成的。如果您需要控制SELECT中的字段,那么您应该使用联接而不是包含。

使用joins:

Profile.some_scope.joins(:users).select("users.email")

在模型中需要额外的归属。

对于简单关联:

belongs_to :user_restricted, -> { select(:id, :email) }, class_name: 'User'

对于多态关联(例如,:commentable):

belongs_to :commentable_restricted, -> { select(:id, :title) }, polymorphic: true, foreign_type: :commentable_type, foreign_key: :commentable_id

您可以选择任何您想要的belongs_to名称。对于上面给出的示例,您可以使用它们,如Article.featured.includes(:user_restricted)Comment.recent.includes(:commentable_restricted)等。

Rails不支持在includes时选择特定列。你知道,这只是lazy load

它使用ActiveRecord::Associations::Preloader模块在数据实际使用之前加载关联的数据。方法:

def preload(records, associations, preload_scope = nil)
    records = Array.wrap(records).compact
    if records.empty?
      []
    else
      records.uniq!
      Array.wrap(associations).flat_map { |association|
        preloaders_on association, records, preload_scope
      }
    end
 end

preload_scopepreload的第三个参数,是选择指定列的一种方式但不能再懒惰加载了

轨道5.1.6处

relation = Profile.where(id: [1,2,3])
user_columns = {:select=>[:updated_at, :id, :name]}
preloader = ActiveRecord::Associations::Preloader.new
preloader.preload(relation, :user, user_columns)

它将选择您传入的指定列。但是,它只是用于单个关联。您需要为ActiveRecord::Associations::Preloader创建一个补丁,以支持一次加载多个复杂的关联。

以下是补丁的示例

使用方法,例如

我自己想要这个功能,所以请使用它。在你的课堂中包括这个方法

#ACCEPTS字符串格式为"ASSOCIATION_NAME:COLUMN_NAME-COLUMN_NAME"的参数

def self.includes_with_select(*m)
    association_arr = []
    m.each do |part|
      parts = part.split(':')
      association = parts[0].to_sym
      select_columns = parts[1].split('-')
      association_macro = (self.reflect_on_association(association).macro)
      association_arr << association.to_sym
      class_name = self.reflect_on_association(association).class_name 
      self.send(association_macro, association, -> {select *select_columns}, class_name: "#{class_name.to_sym}")
    end
    self.includes(*association_arr)
  end

您将能够调用类似的:Contract.includes_with_select('user:id-name-status', 'confirmation:confirmed-id'),它将选择那些指定的列。

使用Mohanaj的例子,您可以做到这一点:

belongs_to :user_only_fetch_email, -> { select [:id, :email] }, :class_name => "User"

相关内容

最新更新