Rails has_one vs belongs_to semantics

Posted by Anurag on Stack Overflow See other posts from Stack Overflow or by Anurag
Published on 2010-01-25T22:18:26Z Indexed on 2010/05/28 18:21 UTC
Read the original article Hit count: 197

Filed under:
|
|

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. For example, the Content model refers to the Image model twice (profile image, and background image). I am trying to avoid a generic has_many, and sticking to multiple has_one's. The current database structure looks like:

contents
  - id:integer
  - integer:profile_image_id
  - integer:background_image_id

images
  - integer:id
  - string:filename
  - integer:content_id

I just can't figure out how to setup the associations correctly here. The Content model could contain two belongs_to references to an Image, but that doesn't seem semantically right cause ideally an image belongs to the content, or in other words, the content has two images.

This is the best I could think of (by breaking the semantics):

class Content
  belongs_to :profile_image, :class_name => 'Image', :foreign_key => 'profile_image_id'
  belongs_to :background_image, :class_name => 'Image', :foreign_key => 'background_image_id'
end

Am I way off, and there a better way to achieve this association?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about model