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