Rails has_one vs belongs_to semantics

后端 未结 2 1761
猫巷女王i
猫巷女王i 2020-12-24 14:30

I have a model representing a Content item that contains some images. The number of images are fixed as these image references are very specific to the content.

2条回答
  •  -上瘾入骨i
    2020-12-24 14:59

    Based on the AR associations guide, I think you should use has_one. It doesn't make sense for an image to own a Content... the Content surely owns the image. From the guide:

    The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association), but you should give some thought to the actual meaning of the data as well. The has_one relationship says that one of something is yours – that is, that something points back to you.

    Finally, I'm not sure you need both contents and images to have foreign keys. As long as the images references the content_id, I think you're alright.

提交回复
热议问题