[英]eager load ActiveRecord polymorphic associations that are 'has_one'
[英]Eager loading polymorphic associations with different has_one associations in Rails 2
当您尝试快速加载不存在的关联时,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停止bit吟和抱怨,它们可能会或可能不会附加某些has_one关联?
我知道这可能只是出于示例的目的,但是您可以将其更改为has_many :complaints
以便它们都具有相同的关联,然后从中提取主要或次要类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.