Rails HABTM with polymorphic relationships

前端 未结 1 691
情话喂你
情话喂你 2021-02-10 21:45

I have a table Category which can have many Businesses and Posts. And a Business/Post can have many Categ

1条回答
  •  深忆病人
    2021-02-10 21:58

    Similar questions here: Rails polymorphic has_many :through And here: ActiveRecord, has_many :through, and Polymorphic Associations

    I think it should be something like this:

    class Category
      has_many :categorizations
      has_many :businesses, through: :categorizations, source: :categorizable, source_type: 'Business'
      has_many :posts, through: :categorizations, source: :categorizable, source_type: 'Post'
    end
    
    class Categorization
      belongs_to :category
      belongs_to :categorizable, polymorphic: true
    end
    
    class Business #Post looks the same
      has_many :categorizations, as: :categorizeable
      has_many :categories, through: :categorizations
    end
    

    0 讨论(0)
提交回复
热议问题