Rails: Many to many polymorphic relationships

前端 未结 7 2058
孤城傲影
孤城傲影 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 01:07

    Although the answer proposed by by SFEley is great, there a some flaws:

    • The retrieval of tasks from target (Store/Vehicle) works, but the backwards wont. That is basically because you can't traverse a :through association to a polymorphic data type because the SQL can't tell what table it's in.
    • Every model with a :through association need a direct association with the intermediate table
    • The :through Assignment association should be in plural
    • The :as statement wont work together with :through, you need to specify it first with the direct association needed with the intermediate table

    With that in mind, my simplest solution would be:

    class Assignment < ActiveRecord::Base
      belongs_to :task
      belongs_to :target, :polymorphic => true
    end
    
    class Task < ActiveRecord::Base
      has_many :assignments
      # acts as the the 'has_many targets' needed
      def targets
        assignments.map {|x| x.target}
      end
    end
    
    class Store < ActiveRecord::Base
      has_many :assignments, as: :target
      has_many :tasks, :through => :assignment
    end
    
    class Vehicle < ActiveRecord::Base
      has_many :assignments, as: :target
      has_many :tasks, :through => :assignment, :as => :target
    end
    

    References: http://blog.hasmanythrough.com/2006/4/3/polymorphic-through

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