【发布时间】:2010-01-25 22:18:26
【问题描述】:
我有一个模型代表一个包含一些图像的Content 项目。图像的数量是固定的,因为这些图像引用非常特定于内容。例如,Content 模型两次引用Image 模型(个人资料图像和背景图像)。我试图避免使用通用的has_many,并坚持使用多个has_one。当前的数据库结构如下:
contents
- id:integer
- integer:profile_image_id
- integer:background_image_id
images
- integer:id
- string:filename
- integer:content_id
我只是不知道如何在这里正确设置关联。 Content 模型可以包含两个 belongs_to 对 Image 的引用,但这在语义上似乎不正确,因为理想情况下图像属于内容,或者换句话说,内容有两个图像。
这是我能想到的最好的(通过打破语义):
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
我离得远吗,还有更好的方法来实现这种关联吗?
【问题讨论】:
标签: ruby-on-rails model associations