我有模特简介。个人资料has_one用户。用户模型有现场电子邮件。我打电话的时候
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没有传递包含查询选项的功能。但我们可以通过模型下的关联声明传递这些参数。
对于您的场景,您需要在配置文件模型下创建与用户模型的新关联,如下所示
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)
您需要额外属于模型。
简单关联:
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)
等。
我自己想要这个功能,所以请使用它。在您的课程中包含此方法
#ACCEPTS以字符串格式args“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')
一样调用它,它将选择那些指定的列。
当includes
时,Rails不支持选择特定的列。你知道,这只是lazy load
。
它使用ActiveRecord::Associations::Preloader模块在数据实际使用之前加载相关数据。通过method:
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_scope
是preload
的第三个参数,是一种选择指定列的方法。但是不能再懒了。
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
创建一个补丁,以支持一次加载多个复杂关联。
使用Mohanaj的示例,您可以这样做:
belongs_to :user_only_fetch_email, -> { select [:id, :email] }, :class_name => "User"