Rails Polymorphic has_many

前端 未结 5 1535
眼角桃花
眼角桃花 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:33

    Here is the workaround I'm currently using. It doesn't provide any of the convenience methods (collection operations) that you get from real ActiveRecord::Associations, but it does provide a way to get the list of products for a given producer:

    class Bicycle < ActiveRecord::Base
      belongs_to :producer
    end
    
    class Popsicle < ActiveRecord::Base
      belongs_to :producer
    end
    
    class Producer < ActiveRecord::Base
      PRODUCT_TYPE_MAPPING = {
        'bicycle' => Bicycle,
        'popsicle' => Popsicle
      }.freeze
      def products
        klass = PRODUCT_TYPE_MAPPING[self.type]
        klass ? klass.find_all_by_producer_id(self.id) : []
      end
    end
    

    Another downside is that I must maintain the mapping of type strings to type classes but that could be automated. However, this solution will suffice for my purposes.

提交回复
热议问题