Rails: Many to many polymorphic relationships

前端 未结 7 2146
孤城傲影
孤城傲影 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

    Using STI:

    class Task < ActiveRecord::Base
    end
    
    class StoreTask < Task
      belongs_to :store, :foreign_key => "target_id"
    end
    
    class VehicleTask < Task
      belongs_to :vehicle, :foreign_key => "target_id"
    end
    
    class Store < ActiveRecord::Base
      has_many :tasks, :class_name => "StoreTask", :foreign_key => "target_id"
    end
    
    class Vehicle < ActiveRecord::Base
      has_many :tasks, :class_name => "VehicleTask", :foreign_key => "target_id"
    end
    

    In your databse you'll need: Task type:string and Task target_id:integer

    The advantage is that now you have a through model for each task type which can be specific.

    See also STI and polymorphic model together

    Cheers!

提交回复
热议问题