Topic: Polymorphic association problem

Argh.  I hate polymorphic associations.  They really make me want to bang my head against something very very hard!

Anyway, here's my question.  I have a polymorphic model called Link.  It can belong to a Task (as well as other things).  My model is set up fine and I'm okay creating a Link that's related to a Task.  My problem is, how to I access the Task (or whatever) that the Link is related to.  I can't call link.task, right?  I thought maybe I could do task = Task.find(link.linkable_id) but that doesn't work either.  Pretty much anything I do it complains that "task" is not a valid constant.  Of course, even if I can get it working it doesn't solve the fact that I won't normally know whether it's a task or not.  I've found lots of blogs that mention polymorphic associations but I haven't found anything that really explains how to use them.


Re: Polymorphic association problem

Good question. Polymorphic association is one of those things you learn through experimenting. To grab the task (or whatever else the link belongs to) you would do this:

link.linkable # returns Task or whatever else

If you want to see if it's really a task you can do this:

if link.linkable.kind_of? Task
  # do something to the task

If this is reporting an error, please post the code in context as well as the full error message.

Railscasts - Free Ruby on Rails Screencasts

Re: Polymorphic association problem

Thanks.  I've found the problem.  After all that it wasn't my code but my fixtures!  I had the linkable_type as "task" and not "Task"!  It's always the little things that trip me up!