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]})
上述代码具有有趣的特性。如果你只有
Bitchy
作为你的类人生物-它实际上会起作用。然而,一旦一个人
Whiny
看来你有麻烦了。ActiveRecord开始抱怨我在上面写的错误-找不到名为“二级投诉”的关联。你明白为什么了吧?因为
不是每一个
人形有一个次要的抱怨。
有没有一种方法可以让ActiveRecord在我试图加载多态关联时停止发牢骚和抱怨,这些关联可能或不一定与它们有一个关联?