Rails: Many to many polymorphic relationships

前端 未结 7 2059
孤城傲影
孤城傲影 2021-01-30 00:17

See comments for updates.

I\'ve been struggling to get a clear and straight-forward answer on this one, I\'m hoping this time I\'ll get it! :D I definitely have

7条回答
  •  后悔当初
    2021-01-30 00:59

    You can combine polymorphism and has_many :through to get a flexible mapping:

    class Assignment < ActiveRecord::Base
      belongs_to :task
      belongs_to :target, :polymorphic => true
    end
    
    class Task < ActiveRecord::Base
      has_many :targets, :through => :assignment
    end
    
    class Store < ActiveRecord::Base
      has_many :tasks, :through => :assignment, :as => :target
    end
    
    class Vehicle < ActiveRecord::Base
      has_many :tasks, :through => :assignment, :as => :target
    end
    

    ...And so forth.

提交回复
热议问题