Belongs_to 和 Has_one 在同一模型中 [英] Belongs_to and Has_one in same model
问题描述
我有两个模型:摄影师和图片.一个摄影师有几张照片,一张照片属于一个摄影师.因此,模型摄影师我实施了政策 has_many:pictures 和模型图片属于 :photographer.
I have two models: Photographer and Picture. A photographer has several pictures and a picture belongs to a photographer. Thus, the model Photographer I implemented the policy has_many:pictures and on the model Picture belongs_to :photographer.
好了.但是,摄影师可以选择一张图片作为您个人资料的封面.因此,我将字段cover_id 添加到表中并指向模型Photographerbelongs_to :cover, class_name: "Image".我的问题是如何在另一端显示这个关系,模型图片,已经和belongs_to :photographer有关系.
All right here. However, a photographer can choose an picture for the cover of your profile. So, I added the field cover_id to the table and pointed the model Photographer belongs_to :cover, class_name: "Image". My problem is how to display this relationship at the other end, the model Picture, which already has a relationship with belongs_to :photographer.
我想我会添加一个图片字段来表明情况会是这样,但是,这个解决方案可以让同一位摄影师获得更多的封面.
Thought I'd add a picture field indicating that this would be the case, however, this solution would allow more than a cover for the same photographer.
补充问题,我应该在 Rails 中强制指定关系的两端吗?
Complementing the question, I should obligatorily specify both ends of a relationship in Rails?
谢谢
推荐答案
我首先认为(个人资料)图片不属于摄影师.相反,摄影师应该有一张个人资料照片.而这种相同类型的物体也可以扮演摄影师拥有但用于个人资料照片以外目的的照片的角色.我认为 STI 是有道理的.
I would first argue that a (profile) picture does not own a photographer. Instead, a photographer should have one profile picture. And this same type of object can also play the role of pictures that the photographer owns but used for purposes other than a profile photo. I think STI make s sense.
class Photographer < ActiveRecord::Base
has_many :pictures
has_one :profile_picture
end
class Picture < ActiveRecord::Base
belongs_to :photographer
end
class ProfilePicture < Picture
belongs_to :photographer
end
通过这种方式,您可以为摄影师分配一张个人资料照片,也可以使用相同的数据库表为两个相似模特创建多张照片.
This way you can assign the one profile picture for the photographer as well as create many pictures using the same database table for both like-models.
photographer = Photographer.create!
profile_picture = ProfilePicture.create!
photographer.profile_picture = profile_picture
photographer.save!
photographer.pictures.create!
photographer.pictures.create!
photographer.pictures.count #=> 3
这篇关于Belongs_to 和 Has_one 在同一模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!