Mat*_*ins 3 ruby-on-rails query-optimization eager-loading ruby-on-rails-3
我正试图在我的Rails 3应用程序中加载.我把它缩小到一个非常基本的样本,而不是生成我期望的一个查询,它产生4.
首先,这是我的模型的简单细分.
class Profile < ActiveRecord::Base
belongs_to :gender
def to_param
self.name
end
end
class Gender < ActiveRecord::Base
has_many :profiles, :dependent => :nullify
end
Run Code Online (Sandbox Code Playgroud)
然后我有一个ProfilesController :: show动作,我在那里查询模型.
def ProfilesController < ApplicationController
before_filter :find_profile, :only => [:show]
def show
end
private
def find_profile
@profile = Profile.find_by_username(params[:id], :include => :gender)
raise ActiveRecord::RecordNotFound, "Page not found" unless @profile
end
end
Run Code Online (Sandbox Code Playgroud)
当我查看生成的查询时,它显示以下内容:
SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`username` = 'matt' LIMIT 1
SELECT `genders`.* FROM `genders` WHERE (`genders`.`id` = 1)
Run Code Online (Sandbox Code Playgroud)
我期望看到的是一个查询:
SELECT `profiles`.*, `genders`.* FROM `profiles` LEFT JOIN `genders` ON `profiles`.gender_id = `genders`.id WHERE `profiles`.`username` = 'matt' LIMIT 1
Run Code Online (Sandbox Code Playgroud)
谁知道我在做错了什么?我在热切加载时发现的一切都让它看起来应该有效.
编辑:尝试后joins,按照雪橇的建议,我仍然看到相同的结果.
代码:
@profile = Profile.joins(:gender).where(:username => params[:id]).limit(1).first
Run Code Online (Sandbox Code Playgroud)
查询:
SELECT `profiles`.* FROM `profiles` INNER JOIN `genders` ON `genders`.`id` = `profiles`.`gender_id` WHERE `profiles`.`username` = 'matt' LIMIT 1
Run Code Online (Sandbox Code Playgroud)
同样,您可以看到没有genders检索到任何数据,因此genders正在进行第二次查询.
我甚至尝试添加一个select,但无济于事:
@profile = Profile.joins(:gender).select('profiles.*, genders.*').where(:username => params[:id]).limit(1).first
Run Code Online (Sandbox Code Playgroud)
这正确导致:
SELECT profiles.*, genders.* FROM `profiles` INNER JOIN `genders` ON `genders`.`id` = `profiles`.`gender_id` WHERE `profiles`.`username` = 'matt' LIMIT 1
Run Code Online (Sandbox Code Playgroud)
...但是genders在访问@profile.gender的属性时它仍会在稍后执行第二次查询.
编辑2:我也尝试创建一个范围既包括select与joins为了得到我所需要的所有领域,(类似于定制左加入证明方法SLED).它看起来像这样:
class Profile < ActiveRecord::Base
# ...
ALL_ATTRIBUTES = [:photo, :city, :gender, :relationship_status, :physique, :children,
:diet, :drink, :smoke, :drug, :education, :income, :job, :politic, :religion, :zodiac]
scope :with_attributes,
select((ALL_ATTRIBUTES.collect { |a| "`#{reflect_on_association(a).table_name}`.*" } + ["`#{table_name}`.*"]).join(', ')).
joins(ALL_ATTRIBUTES.collect { |a|
assoc = reflect_on_association(a)
"LEFT JOIN `#{assoc.table_name}` ON `#{table_name}`.#{assoc.primary_key_name} = `#{assoc.table_name}`.#{assoc.active_record_primary_key}"
}.join(' '))
# ...
end
Run Code Online (Sandbox Code Playgroud)
这会生成以下查询,该查询显示正确:
SELECT `photos`.*, `cities`.*, `profile_genders`.*, `profile_relationship_statuses`.*, `profile_physiques`.*, `profile_children`.*, `profile_diets`.*, `profile_drinks`.*, `profile_smokes`.*, `profile_drugs`.*, `profile_educations`.*, `profile_incomes`.*, `profile_jobs`.*, `profile_politics`.*, `profile_religions`.*, `profile_zodiacs`.*, `profiles`.* FROM `profiles` LEFT JOIN `photos` ON `profiles`.photo_id = `photos`.id LEFT JOIN `cities` ON `profiles`.city_id = `cities`.id LEFT JOIN `profile_genders` ON `profiles`.gender_id = `profile_genders`.id LEFT JOIN `profile_relationship_statuses` ON `profiles`.relationship_status_id = `profile_relationship_statuses`.id LEFT JOIN `profile_physiques` ON `profiles`.physique_id = `profile_physiques`.id LEFT JOIN `profile_children` ON `profiles`.children_id = `profile_children`.id LEFT JOIN `profile_diets` ON `profiles`.diet_id = `profile_diets`.id LEFT JOIN `profile_drinks` ON `profiles`.drink_id = `profile_drinks`.id LEFT JOIN `profile_smokes` ON `profiles`.smoke_id = `profile_smokes`.id LEFT JOIN `profile_drugs` ON `profiles`.drug_id = `profile_drugs`.id LEFT JOIN `profile_educations` ON `profiles`.education_id = `profile_educations`.id LEFT JOIN `profile_incomes` ON `profiles`.income_id = `profile_incomes`.id LEFT JOIN `profile_jobs` ON `profiles`.job_id = `profile_jobs`.id LEFT JOIN `profile_politics` ON `profiles`.politic_id = `profile_politics`.id LEFT JOIN `profile_religions` ON `profiles`.religion_id = `profile_religions`.id LEFT JOIN `profile_zodiacs` ON `profiles`.zodiac_id = `profile_zodiacs`.id WHERE `profiles`.`username` = 'matt' LIMIT 1
Run Code Online (Sandbox Code Playgroud)
不幸的是,对关系属性(例如:)的调用似乎并没有@profile.gender.name使用原始SELECT中返回的数据.相反,我看到第一个后面的大量查询:
Profile::Gender Load (0.2ms) SELECT `profile_genders`.* FROM `profile_genders` WHERE `profile_genders`.`id` = 1 LIMIT 1
Profile::Gender Load (0.4ms) SELECT `profile_genders`.* FROM `profile_genders` INNER JOIN `profile_attractions` ON `profile_genders`.id = `profile_attractions`.gender_id WHERE ((`profile_attractions`.profile_id = 2))
City Load (0.4ms) SELECT `cities`.* FROM `cities` WHERE `cities`.`id` = 1 LIMIT 1
Country Load (0.3ms) SELECT `countries`.* FROM `countries` WHERE `countries`.`id` = 228 ORDER BY FIELD(code, 'US') DESC, name ASC LIMIT 1
Profile Load (0.4ms) SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`id` = 2 LIMIT 1
Profile::Language Load (0.4ms) SELECT `profile_languages`.* FROM `profile_languages` INNER JOIN `profile_profiles_languages` ON `profile_languages`.id = `profile_profiles_languages`.language_id WHERE ((`profile_profiles_languages`.profile_id = 2))
SQL (0.3ms) SELECT COUNT(*) FROM `profile_ethnicities` INNER JOIN `profile_profiles_ethnicities` ON `profile_ethnicities`.id = `profile_profiles_ethnicities`.ethnicity_id WHERE ((`profile_profiles_ethnicities`.profile_id = 2))
Profile::Religion Load (0.5ms) SELECT `profile_religions`.* FROM `profile_religions` WHERE `profile_religions`.`id` = 2 LIMIT 1
Profile::Politic Load (0.2ms) SELECT `profile_politics`.* FROM `profile_politics` WHERE `profile_politics`.`id` = 3 LIMIT 1
Run Code Online (Sandbox Code Playgroud)
你的例子很好,它最终将在两个查询中,因为这是在rails中实现的急切加载.如果您有许多相关记录,它会变得很方便.你可以在这里阅读更多相关信息
你可能想要的是一个简单的连接:
@profile = Profile.joins(:gender).where(:username => params[:id])
Run Code Online (Sandbox Code Playgroud)
编辑
如果配置文件由许多部分组成,则有多种方法:
自定义左连接 - 也许有一个插件可以完成工作,否则我建议做一些像:
class Profile < ActiveRecord::Base
# .... code .....
def self.with_dependencies
attr_joins = []
attr_selects = []
attr_selects << "`profiles`.*"
attr_selects << "`genders`.*"
attr_selects << "`colors`.*"
attr_joins << "LEFT JOIN `genders` ON `gender`.`id` = `profiles`.gender_id"
attr_joins << "LEFT JOIN `colors` ON `colors`.`id` = `profiles`.color_id"
prep_model = select(attr_selects.join(','))
attr_joins.each do |c_join|
prep_model = prep_model.joins(c_join)
end
return prep_model
end
end
Run Code Online (Sandbox Code Playgroud)
现在你可以这样做:
@profile = Profile.with_dependencies.where(:username => params[:id])
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是使用:include => [:gender, :color]它可能是一些查询更多,但它是更干净的"轨道方式".如果遇到性能问题,您可能需要重新考虑数据库架构,但是您真的有这么大的负载吗?
我的一个朋友为这个简单的1:n关系(如性别)写了一个很好的小解决方案,它被称为simple_enum
| 归档时间: |
|
| 查看次数: |
1047 次 |
| 最近记录: |