在这种情况下,我应该如何指定 Rails 模型关系?
How should I specify Rails model relationship in this case?
假设我在Rails中有3个模型:Post、评论和用户。他们每个人都应该与图像模型具有一对一的关系。
我应该选择:
class Post
has_one :image
end
class Comment
has_one :image
end
class User
has_one :image
end
class Image
# Foreign key references
belongs_to :post
belongs_to :comment
belongs_to :user
end
或
class Post
belongs_to :image # Foreign key reference
end
class Comment
belongs_to :image # Foreign key reference
end
class User
belongs_to :image # Foreign key reference
end
class Image
end
各自的优缺点是什么?
还有其他众所周知的做法可以处理这种情况吗?
根据给定的数据,两者之间没有真正的区别。
然而...
日后...如果您突然决定 post 需要两张图片,您需要在图片上添加 post_id,而不是 image_id post(否则你会陷入只能为 post 制作一张图片)的困境。
这意味着您最好在图像方面使用 belongs_to,而不是其他方面。
假设我在Rails中有3个模型:Post、评论和用户。他们每个人都应该与图像模型具有一对一的关系。
我应该选择:
class Post
has_one :image
end
class Comment
has_one :image
end
class User
has_one :image
end
class Image
# Foreign key references
belongs_to :post
belongs_to :comment
belongs_to :user
end
或
class Post
belongs_to :image # Foreign key reference
end
class Comment
belongs_to :image # Foreign key reference
end
class User
belongs_to :image # Foreign key reference
end
class Image
end
各自的优缺点是什么? 还有其他众所周知的做法可以处理这种情况吗?
根据给定的数据,两者之间没有真正的区别。
然而... 日后...如果您突然决定 post 需要两张图片,您需要在图片上添加 post_id,而不是 image_id post(否则你会陷入只能为 post 制作一张图片)的困境。
这意味着您最好在图像方面使用 belongs_to,而不是其他方面。