当您尝试加载一个不存在的关联时,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开始抱怨我上面写的错误-没有找到名为“secondary_complaint”的关联。你知道为什么吧?因为不是每个人都有secondary_complaint。
当我试图加载多态关联时,是否有一种方法可以让ActiveRecord停止抱怨和抱怨,因为多态关联可能或可能没有某些has_one关联附加到它们上?
发布于 2010-06-20 21:27:20
我知道这可能只是为了您的示例,但您可以将其更改为has_many :complaints,以便它们具有相同的关联,然后从中提取主类型或次要类型。
https://stackoverflow.com/questions/3078315
复制相似问题