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
zetetic
source share