Rails Polymorphic has_many

前端 未结 5 1544
眼角桃花
眼角桃花 2020-12-31 07:44

Using Ruby on Rails, how can I achieve a polymorphic has_many relationship where the owner is always of a known but the items in the association will be of some

5条回答
  •  太阳男子
    2020-12-31 08:12

    You have to use STI on the producers, not on the products. This way you have different behavior for each type of producer, but in a single producers table.

    (almost) No polymorphism at all!

    class Product < ActiveRecord::Base
      # does not have a 'type' column, so there is no STI here,
      # it is like an abstract superclass.
      belongs_to :producer
    end
    
    class Bicycle < Product
    end
    
    class Popsicle < Product
    end
    
    class Producer < ActiveRecord::Base
      # it has a 'type' column so we have STI here!!
    end
    
    class BicycleProducer < Producer
      has_many :products, :class_name => "Bicycle", :inverse_of => :producer
    end
    
    class PopsicleProducer < Producer
      has_many :products, :class_name => "Popsicle", :inverse_of => :producer
    end
    

提交回复
热议问题