I have a parent object, Post, which has the following children.
has_one :link
has_one :picture
has_one :code
These children are mutually ex
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
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
I wrote up a small Gist showing how to do this: https://gist.github.com/1242485