Rails: Many to many polymorphic relationships

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

    This may not be an especially helpful answer, but stated simply, I don't think there is an easy or automagic way to do this. At least, not as easy as with simpler to-one or to-many associations.

    I think that creating an ActiveRecord model for the join table is the right way to approach the problem. A normal has_and_belongs_to_many relationship assumes a join between two specified tables, whereas in your case it sounds like you want to join between tasks and any one of stores, softwares, offices, or vehicles (by the way, is there a reason not to use STI here? It seems like it would help reduce complexity by limiting the number of tables you have). So in your case, the join table would also need to know the name of the Target subclass involved. Something like

    create_table :targets_tasks do |t|
      t.integer :target_id
      t.string :target_type
      t.integer :task_id
    end
    

    Then, in your Task class, your Target subclasses, and the TargetsTask class, you could set up has_many associations using the :through keyword as documented on the ActiveRecord::Associations::ClassMethods rdoc pages.

    But still, that only gets you part of the way, because :through won't know to use the target_type field as the Target subclass name. For that, you might be able to write some custom select/finder SQL fragments, also documented in ActiveRecord::Associations::ClassMethods.

    Hopefully this gets you moving in the right direction. If you find a complete solution, I'd love to see it!

提交回复
热议问题