Reverse Polymorphic Associations

后端 未结 3 2028
北荒
北荒 2021-01-05 13:42

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

相关标签:
3条回答
  • 2021-01-05 14:05

    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

    0 讨论(0)
  • 2021-01-05 14:15

    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
    
    0 讨论(0)
  • 2021-01-05 14:21

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

    0 讨论(0)
提交回复
热议问题