Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>I think that creating an ActiveRecord model for the join table is the right way to approach the problem. A normal <code>has_and_belongs_to_many</code> relationship assumes a join between two specified tables, whereas in your case it sounds like you want to join between <code>tasks</code> and any one of <code>stores</code>, <code>softwares</code>, <code>offices</code>, or <code>vehicles</code> (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 <code>Target</code> subclass involved. Something like</p> <pre><code>create_table :targets_tasks do |t| t.integer :target_id t.string :target_type t.integer :task_id end </code></pre> <p>Then, in your <code>Task</code> class, your <code>Target</code> subclasses, and the <code>TargetsTask</code> class, you could set up <code>has_many</code> associations using the <code>:through</code> keyword as documented on the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M002123" rel="nofollow noreferrer" title="ActiveRecord::Associations::ClassMethods">ActiveRecord::Associations::ClassMethods rdoc pages</a>.</p> <p>But still, that only gets you part of the way, because <code>:through</code> won't know to use the <code>target_type</code> field as the <code>Target</code> subclass name. For that, you might be able to write some custom select/finder SQL fragments, also documented in <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M002123" rel="nofollow noreferrer" title="ActiveRecord::Associations::ClassMethods">ActiveRecord::Associations::ClassMethods</a>.</p> <p>Hopefully this gets you moving in the right direction. If you find a complete solution, I'd love to see it!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload