views:

52

answers:

2

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?

A: 

I believe you are looking for the :as option for has_one. It allows you to specify the name of the belongs_to association end.

When all else fails, read the docs: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_one

ihoka
Maybe I'm missing something, but how would I create a dynamic association with a child using :as?I understand polymorphism in regards to how a child object could have any type of parent object. But what I am asking is how a parent object can have any type of child object.I want to do something like @post.postable and get the child object, which would be one of link, picture, or code.
Jared Brown
A: 

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?

has_one implies that the foreign key is in the other table. If you've really defined your model this way, then you won't have link_id, picture_id, and code_id in your Post table. I think you meant to say belongs_to.

I want to do something like @post.postable and get the child object, which would be one of link, picture, or code.

I believe you could do this by using STI and combining the links, pictures, and codes tables, then testing the type of the model when retrieving. That seems kludgey though, and could end up with lots of unused columns.

Is there a reason for not storing the unused id columns, other than saving space? If you're willing to keep them, then you could define a virtual attribute and a postable_type column : (untested code, may fail spectacularly)

def postable
  self.send(self.postable_type)
end

def postable=(p)
  self.send(postable_type.to_s+"=",p)
end
zetetic
I'm just searching for a more elegant way of doing things than having multiple *_id columns. Though as this thread is proving out, the multiple *_id columns approach is probably the simplest and the best.
Jared Brown