Inverse polymorphic associations

I have a parent Post that 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 the reverse order, so that I don't need to have the link_id, picture_id and code_id fields in my Post table?

+5
source share
3 answers

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

+8
source

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

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

0
source

Is there a way to use polymorphic associations in the opposite direction so that I don't need to have link_id, picture_id and code_id in my Message Table?

has_one means that the foreign key is in another table. If you really defined your model this way, you will not have link_id , picture_id and code_id in the Post table. I think you wanted to say belongs_to .

I want to do something like @ post.postable and get a child object that would be one of the links, image or code.

I believe that you could do this by using the STI and combining the links , pictures and codes tables, and then checking the model type when retrieving. This is similar to kludgey, although it may end up with many unused columns.

Is there any reason not to store id columns id except save space? If you want to keep them, then you can define a virtual attribute and a postable_type column: (unverified code may postable_type to appear)

 def postable self.send(self.postable_type) end def postable=(p) self.send(postable_type.to_s+"=",p) end 
0
source

All Articles