views:

245

answers:

1

Hi, I have a many to one polymorphic rails association in my rails app for a 'case' model. There are many things that have cases, so I access the case each thing has by doing 'thing_that_has_a_case.case'.

However, I'm trying to go the other way and I'm not sure how. I have access to the case object but I want to access the thing that is being cased. Does rails have a way to do this? I could do it with an ugly switch that does a different sql find for each type of object, but I was hoping rails would have a better way. Thanks!

+2  A: 

You can add something like this to your case model:

belongs_to :parent, :polymorphic => true

..which assumes you have fields parent_id and parent_type in your case model (change the first argument to the belongs_to depending on how you have named these association fields). Once you have this, you should just be able to refer to case.parent for a given case instance.

And, just to clarify, the one side of this relationship has something like:

has_many :cases, :as => :parent, :dependent => :destroy

(I'm assuming you already have that working based on your description)

Mike Ellery
Thanks, works now.
William