Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Polymorphic Associations

I have a parent object, Post, which has the following children.

has_one :link
has_one :picture
has_one :code

These children are mutually exclusive.

Is there a way to use polymorphic associations in reverse so that I don't have to have link_id, picture_id, and code_id fields in my Post table?

like image 264
Jared Brown Avatar asked Aug 15 '10 14:08

Jared Brown


People also ask

What is polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

Is polymorphism a type of association?

Polymorphic association is a term used in discussions of Object-Relational Mapping with respect to the problem of representing in the relational database domain, a relationship from one class to multiple classes.

How is polymorphic association set up in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.


1 Answers

I wrote up a small Gist showing how to do this: https://gist.github.com/1242485

like image 152
Ronze Avatar answered Sep 30 '22 19:09

Ronze