Rails polymorphic many to many association

后端 未结 4 392
无人及你
无人及你 2021-02-04 21:39

I\'m trying setup a generic sort of web of related objects. Let say I have 4 models.

  • Book
  • Movie
  • Tag
  • Category

I would lik

4条回答
  •  伪装坚强ぢ
    2021-02-04 22:16

    depending on how closesly related your movies/books db tables are

    what if you declared

    class Items < ActiveRecord::Base
      has_many :tags
      has_many :categories
      has_and_belongs_to_many :related_items,
           :class => "Items",
           :join_table => :related_items,
           :foreign_key => "item_id",
           :associated_foreign_key => "related_item_id"
    end
    
    class Books < Items
    class Movies < Items
    

    make sure you put type in your items table

提交回复
热议问题