简体   繁体   English

关于belong_to,has_one,has_many的困惑

[英]Confusion regarding belong_to, has_one, has_many

I am trying to extend the function of a Shift model in my project. 我正在尝试在我的项目中扩展Shift模型的功能。 I have two types of shifts Ashift and Bshift, that are immediately related to Shift. 我有两种类型的班次Ashift和Bshift,它们与Shift直接相关。

My confusion stems from how to set up the associations in Shift. 我的困惑源于如何在Shift中建立关联。 This is what I have: 这就是我所拥有的:

I am trying to say that Shift has one or the other dependent shift class, but not both, and also not neither. 我要说的是Shift具有一个或另一个从属的班次,但没有两个,也没有。

class Ashift < ApplicationRecord
  belongs_to :shift
end
class Bshift < ApplicationRecord
  belongs_to :shift
end

class Shift < ApplicationRecord
  has_one :ashift
  has_one :bshift
end

I am sure this is clearly laid out in the association guide but I've read it a couple of times, and I am still subtlety confused. 我确定这在协会指南中已明确列出,但我已经阅读了几次,但我仍然很困惑。

Does has_one, or has_many, refer to each instance of the model, or the Model class as a whole? has_one或has_many是否引用模型的每个实例或整个Model类? Is there a different, or better way of doing this? 是否有其他更好的方法?

use has one and STI readmore about this here 使用有一个和性传播感染 在这里了解更多

class TheShift < ApplicationRecord
  belongs_to :shift
end

class Ashift < TheShift 
end

class Bshift < TheShift 
end

class Shift < ApplicationRecord
  has_one :theshift
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM