代码之家  ›  专栏  ›  技术社区  ›  Jamie Rumbelow

同一模型上具有多个关联的多态关联

  •  9
  • Jamie Rumbelow  · 技术社区  · 17 年前

    我在文章模型中使用了此关联:

    class Article < ActiveRecord::Base
      has_one :header_image, :as => :imageable
      has_many :images, :as => :imageable
    end
    

    2 回复  |  直到 17 年前
        1
  •  7
  •   Robert    16 年前

    我尝试了这个,但是header_image返回了其中一个图像。只是因为images表没有指定不同的图像使用类型(header\u image与normal image)。它只是说:imageable_type=两种用途的图像。因此,如果没有存储有关使用类型的信息,ActiveRecord将无法区分。

        2
  •  4
  •   mylescarrick    17 年前

    是的。这是完全可能的。

    header_image ,因为这是无法推断的。包括 :dependent => :destroy 同样,为了确保删除文章时图像被销毁

    class Article < ActiveRecord::Base
      has_one :header_image, :as => :imageable, :class_name => 'Image', :dependent => :destroy
      has_many :images, :as => :imageable, :dependent => :destroy
    end
    

    class Image < ActiveRecord::Base
      belongs_to :imageable, :polymorphic => true
    end
    
    推荐文章