我有一组与地理相关的课程:州,Msa,县,城市等等。这些类都是从一个基址类上来的。这些类在很大程度上是通过一个称为地理的非规范化连接表来关联的。所以我有..。
class Geography < ActiveRecord::Base
belongs_to :state
belongs_to :county
belongs_to :city
# ... etc.
end
class Location < ActiveRecord::Base
end
class State < Location
has_many :geographies
has_many :msas, :through => :geographies, :uniq => true
# ... etc.
end
class Msa < Location
has_many :geographies
has_many :states, :through => :geographies, :uniq => true
# ... etc.
end现在,当我从控制台运行以下内容时:
>> msas = Msa.find(:all, :include=>"states", :conditions=>{"states_locations"=>{"id"=>"1"}})我得到了正确的结果数(本例中为13)。但是,运行这个find调用产生的SQL,我得到了1,00个结果(同样,地理表是一个数据类型,这就是为什么我在关联中使用:uniq选项的原因)。
SELECT `locations`.`id` AS t0_r0,
`locations`.`parent_id` AS t0_r1,
`locations`.`type` AS t0_r2,
`locations`.`name` AS t0_r3,
`states_locations`.`id` AS t1_r0,
`states_locations`.`parent_id` AS t1_r1,
`states_locations`.`type` AS t1_r2,
`states_locations`.`name` AS t1_r3
FROM `locations`
LEFT OUTER JOIN `geography`
ON `locations`.`id` = `geography`.`msa_id`
LEFT OUTER JOIN `locations` states_locations
ON `states_locations`.`id` = `geography`.`state_id`
AND `states_locations`.`type` = 'State'
WHERE `states_locations`.`id` = '1'
AND `locations`.`type` = 'Msa' 我假设这意味着Rails正在将1,000多个记录加载到内存中,然后,在Ruby中,将结果减少到不同的Msas集合(在本例中);看起来有点低效。此外,以下后续调用返回不同的结果:
>> msas.first.states.size # incorrect count
=> 192
>> msas.first.states.count # correct count
=> 1
>> msas.first.states # incorrect number of State objects
=> [#<State id: 1, ... >, ..., #<State id: 1, ... >]
>> msas.first.reload.states
=> [#<State id: 1, ... >] # correct number of State objects我的问题是:
任何见解都将不胜感激。
谢谢你,杰森
发布于 2010-01-26 17:53:25
你有很多问题,让我看看能不能帮上忙.
rails将触发一个sql调用以获得所有结果,这是正确的,然后active_record应该筛选出唯一的记录。
如果要避免这种情况,可以执行以下操作:
has_many :states, :through => :geographies, :select => "DISTINCT states.*"
这个帖子有有趣的分析
还有你的台词:
msas = Msa.find(:all, :include=>"states", :conditions=>{"states_locations"=>{"id"=>"1"}})
它没有返回唯一的结果,因为您没有利用您所建立的关系。你可能想做这样的事情:
@msas = State.find(state_id).msas
祝好运
https://stackoverflow.com/questions/2140844
复制相似问题