34

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 a lot to learn still with Rails, however I do understand the problem I'm facing and would really appreciate additional help.

  • I have a model called "Task".
  • I have an abstract model called "Target".
  • I would like to relate multiple instances of subclasses of Target to Task.
  • I am not using single table inheritance.
  • I would like to query the polymorphic relationship to return a mixed result set of subclasses of Target.
  • I would like to query individual instances of subclasses of Target to obtain tasks that they are in a relationship with.

So, I figure a polymorphic many to many relationship between Tasks and subclasses of Targets is in order. In more detail, I will be able to do things like this in the console (and of course elsewhere):

task = Task.find(1)
task.targets
[...array of all the subclasses of Target here...]

But! Assuming models "Store", "Software", "Office", "Vehicle", which are all subclasses of "Target" exist, it would be nice to also traverse the relationship in the other direction:

store = Store.find(1)
store.tasks
[...array of all the Tasks this Store is related to...]
software = Software.find(18)
software.tasks
[...array of all the Tasks this Software is related to...]

The database tables implied by polymorphic relationships appears to be capable of doing this traversal, but I see some recurring themes in trying to find an answer which to me defeat the spirit of polymorphic relationships:

  • Using my example still, people appear to want to define Store, Software, Office, Vehicle in Task, which we can tell right away isn't a polymorphic relationship as it only returns one type of model.
  • Similar to the last point, people still want to define Store, Software, Office and Vehicle in Task in one way shape or form. The important bit here is that the relationship is blind to the subclassing. My polymorphs will initially only be interacted with as Targets, not as their individual subclass types. Defining each subclass in Task again starts to eat away at the purpose of the polymorphic relationship.
  • I see that a model for the join table might be in order, that seems somewhat correct to me except that it adds some complexity I assumed Rails would be willing to do away with. I plea inexperience on this one.

It seems to be a small hole in either rails functionality or the collective community knowledge. So hopefully stackoverflow can chronicle my search for the answer!

Thanks to everyone who help!

7
  • In your six bullet points, five of them are trivial to achieve if you drop the sixth, "I am not using single table inheritance". Regarding your point on STI below, since extra columns really bug you, consider using delegation to push out the additional data and behavior to other models. Jul 15, 2009 at 2:51
  • 2
    Pushing it outwards is what resulted in this. STI though is not an option. I wish it were because, yes...Everyone is a huge fan of it. But I want the stored data to be cohesive and there will be quite a few different types of Targets. I still find it somewhat striking that there isn't a way to pull a mixed collection like this. My design seems fairly sound. Jul 15, 2009 at 3:30
  • I have been able to accomplish most of the functionality I desire through the use of has_many_polymorphs. The one remaining limitation is that I'm still stuck defining each polymorphic type in my parent (Task). Additional solutions are welcome, but I'm not sure a solution will be upon us until a new version of rails or an update to has_many_polymorphs! Jul 15, 2009 at 19:19
  • See the following: rubyforge.org/forum/… Jul 15, 2009 at 19:46
  • 1
    As a frequent dabbler (do a tutorial, wait two years, do a tutorial), I was utterly shocked when I saw that Rails had no baked in support for such a basic concept as this. I realize that the STI pattern is appropriate in many instances, but when the class hierarchy starts to sprawl and the properties on each subclass diverge, it is simply unacceptable to call it a "preferred" approach. It might be easier, even tenable, but it still has the capacity to produce such a mess in the DB that relying solely on STI for all model inheritance smells like an anti-pattern. Aug 23, 2009 at 18:11

7 Answers 7

58

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.

7
  • 2
    This seems to solve the problem very simply and is 100% supported by Rails. Apr 7, 2010 at 21:07
  • 1
    Note that :as => target should be :as => :target in both cases. Nice solution May 6, 2012 at 17:36
  • 3
    I'm getting the equivalent to ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association│ :assignment in model Task when trying to set this up in my application in Rails 3. I'm using modules (both are in the same module), would that cause this error? Nov 20, 2012 at 22:25
  • 4
    I faced the similar problem, but on polymorphic end of relation. I guess this answer is not complete, i added extra has_many :assigments, :as => target to Task and Vehicle models, and has_many :tasks, :through => :assignment, :as => :target is shortened to has_many :tasks, :through => :assignments
    – Dfr
    Dec 12, 2012 at 12:30
  • 1
    I think it should be has_many :assignments and then has_many :targets, :through => :assignments.
    – lobati
    Aug 13, 2013 at 0:15
15

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

1
  • 1
    I know this is three years later, but I'm having a similar issue and trying to wrap my head around your solution. All seems well, but the one difference you have between the Store and Vehicle models is the segment :as => :target on the last line. Was that intentional? Why should Store and Vehicle be any different? Just want to confirm! Aug 12, 2018 at 7:59
1

The has_many_polymorphs solution you mention isn't that bad.

class Task < ActiveRecord::Base
  has_many_polymorphs :targets, :from => [:store, :software, :office, :vehicle]
end

Seems to do everything you want.

It provides the following methods:

to Task:

t = Task.first
t.targets   # Mixed collection of all targets associated with task t
t.stores    # Collection of stores associated with task t
t.softwares # same but for software
t.offices   # same but for office
t.vehicles  # same but for vehicles

to Software, Store, Office, Vehicle:

s = Software.first    # works for any of the subtargets.
s.tasks               # lists tasks associated with s

If I'm following the comments correctly, the only remaining problem is that you don't want to have to modify app/models/task.rb every time you create a new type of Subtarget. The Rails way seems to require you to modify two files to create a bidirectional association. has_many_polymorphs only requires you to change the Tasks file. Seems like a win to me. Or at least it would if you didn't have to edit the new Model file anyway.

There are a few ways around this, but they seem like way too much work to avoid changing one file every once in a while. But if you're that dead set against modifying Task yourself to add to the polymorphic relationship, here's my suggestion:

Keep a list of subtargets, I'm going to suggest in lib/subtargets formatted one entry per line that is essentially the table_name.underscore. (Capital letters have an underscore prefixed and then everything is made lowercase)

store
software
office
vehicle

Create config/initializers/subtargets.rb and fill it with this:

SubtargetList = File.open("#{RAILS_ROOT}/lib/subtargets").read.split.reject(&:match(/#/)).map(&:to_sym)

Next you're going to want to either create a custom generator or a new rake task. To generate your new subtarget and add the model name to the subtarget list file, defined above. You'll probably end up doing something bare bones that makes the change and passes the arguments to the standard generator.

Sorry, I don't really feel like walking you through that right now, but here are some resources

Finally replace the list in the has_many_polymorphs declaration with SubtargetList

class Task < ActiveRecord::Base
  has_many_polymorphs :targets, :from => SubtargetList
end

From this point on you could add a new subtarget with

$ script/generate subtarget_model home

And this will automatically update your polymorphic list once you reload your console or restart the production server.

As I said it's a lot of work to automatically update the subtargets list. However, if you do go this route you can tweak the custom generator ensure all the required parts of the subtarget model are there when you generate it.

1

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!

0

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!

2
  • Trust me, I've been banging my head on this one for a while. As soon as I come up with something, it will be very widely circulated. I'm somewhat surprised that it hasn't been addressed sooner as mixed result sets are all the rage nowadays! :) Jul 14, 2009 at 22:53
  • Also, I'm not using STI because it is inefficient and not the way I want to store my data. I'll likely be associating additional behaviours with subclasses of Target above and beyond the defaults. Big tables with lots of columns just doesn't appeal to me :) Jul 15, 2009 at 1:34
0

I agree with the others I would go for a solution that uses a mixture of STI and delegation would be much easier to implement.

At the heart of your problem is where to store a record of all the subclasses of Target. ActiveRecord chooses the database via the STI model.

You could store them in a class variable in the Target and use the inherited callback to add new ones to it. Then you can dynamically generate the code you'll need from the contents of that array and leverage method_missing.

0

Have you pursued that brute force approach:

class Task 
  has_many :stores
  has_many :softwares
  has_many :offices
  has_many :vehicles

  def targets
    stores + softwares + offices + vehicles
  end
  ...

It may not be that elegant, but to be honest it's not that verbose, and there is nothing inherently inefficient about the code.

2
  • Right, but then Task has to be aware of each type of targetable. I'd like to be able to create a targetable and not have to modify task each time a new one is added. Sep 26, 2009 at 17:21
  • It is ruby. You could write a "belongs_to_task" class method (or a module) to be included in your stores, offices etc. It could modify the Task class, doing what is done above (adding a has_many and patching the targets to include what the class). I'm not recommending that approach, I'm just saying...
    – ndp
    Sep 27, 2009 at 6:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.