代码之家  ›  专栏  ›  技术社区  ›  Max Chernyak

在Rails 2中,与不同的预加载多态关联有一个关联。

  •  2
  • Max Chernyak  · 技术社区  · 16 年前

    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在我试图加载多态关联时停止发牢骚和抱怨,这些关联可能或不一定与它们有一个关联?

    1 回复  |  直到 16 年前
        1
  •  0
  •   Andrew Vit    16 年前

    我知道这可能只是为了你的例子,但是你可以把它改为 has_many :complaints 所以它们都有相同的关联,然后从中拉出主类型或次类型。

    推荐文章