Ruby on rails 在Rails 2中,急切地加载具有不同has_one关联的多态关联

Ruby on rails 在Rails 2中,急切地加载具有不同has_one关联的多态关联,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,当您尝试加载不存在的关联时,ActiveRecord会给您一个有趣的错误。它看起来像这样: ActiveRecord::ConfigurationError: Association named 'secondary_complaint' was not found; perhaps you misspelled it? 现在,为什么会有人想要预加载一个不存在的关联?看看这个 class Bitchy < ActiveRecord::Base has_one :primary_com

当您尝试加载不存在的关联时,ActiveRecord会给您一个有趣的错误。它看起来像这样:

ActiveRecord::ConfigurationError: Association named 'secondary_complaint' was not found; perhaps you misspelled it?
现在,为什么会有人想要预加载一个不存在的关联?看看这个

class Bitchy < ActiveRecord::Base
  has_one :primary_complaint, :as => :whiny_bitch, :class_name => 'Complaint', :conditions => {:complaint_type => 'primary'}
  has_one :secondary_complaint, :as => :whiny_bitch, :class_name => 'Complaint', :conditions => {:complaint_type => 'secondary'}

  has_one :life, :as => :humanoid
end


class Whiny < ActiveRecord::Base
  has_one :primary_complaint, :as => :whiny_bitch, :class_name => 'Complaint', :conditions => {:complaint_type => 'primary'}

  has_one :life, :as => :humanoid
end

class Complaint < ActiveRecord::Base
  belongs_to :whiny_bitch, :polymorphic => true
end

class Life < ActiveRecord::Base
  belongs_to :humanoid, :polymorphic => true
end

# And here's the eager-loading part:
Life.all(:include => {:humanoid => [:primary_complaint, :secondary_complaint]})
class Bitchy:whiny\u bitch,:class\u name=>'complaint',:conditions=>{:complaint\u type=>'primary'}
有一个:次要投诉,:as=>:whiny\u bitch,:class\u name=>'complaint',:conditions=>{:投诉类型=>'secondary'}
有一个:生命,:as=>:类人
结束
类呜呜声:whiny\u bitch,:class\u name=>'complaint',:conditions=>{:complaint\u type=>'primary'}
有一个:生命,:as=>:类人
结束
类投诉true
结束
类生命true
结束
#这里是急切的加载部分:
所有(:include=>{:类人=>[:主要投诉,:次要投诉]})
上面的代码具有有趣的特性。如果你只有
Bitchy
作为你的人形机器人,它将真正起作用。然而,只要出现一个
抱怨声
,你就有麻烦了。ActiveRecord开始抱怨我上面写的错误-找不到名为“secondary_complaint”的关联。你明白为什么了吧?因为不是每个人形生物都有第二个抱怨


当我试图急切地加载多态关联时,有没有办法让ActiveRecord停止抱怨和抱怨?这些多态关联可能有也可能没有特定的has\u one关联附加到它们上?

我知道这可能只是为了您的示例,但您可以将其更改为“has-many:complaints”,这样它们都具有相同的关联,然后从中提取主要或次要类型。

我知道这可能只是为了您的示例,但您可以将其更改为“has-many:complaints”,这样它们都具有相同的关联,然后从中取出主要或次要类型。

我认为您不能这样做:/+1表示创造性对象名称。:-)我认为您不能这样做:/+1用于创造性对象名称。:-)我肯定在考虑切换到has_many,以便优化工作。最糟糕的是,在急切加载中有
[:primary\u complaint,:secondary\u complaint]
是有和没有N+1问题的决定性因素。坦白地说,我甚至不认为它是最优化的,我认为在公共驱动代码中永远不会有N+ 1。但在采用这种方法之前,我很想尝试寻找替代路线。我想通常这是一种更好的方法来实现这一点,同时我禁用了这种情况下的急切加载。稍后将进行优化。接受。:)我肯定在考虑切换到has_many,以便优化工作。最糟糕的是,在急切加载中有
[:primary\u complaint,:secondary\u complaint]
是有和没有N+1问题的决定性因素。坦白地说,我甚至不认为它是最优化的,我认为在公共驱动代码中永远不会有N+ 1。但在采用这种方法之前,我很想尝试寻找替代路线。我想通常这是一种更好的方法来实现这一点,同时我禁用了这种情况下的急切加载。稍后将进行优化。接受。:)