轨,模特协会,儿童属于父母和HAS_ONE父母关系
问题描述:
在我的Rails项目,我想有这样的结构:轨,模特协会,儿童属于父母和HAS_ONE父母关系
的论证有很多争论。
论证属于辩论。
的参数可以有一个论证(一个又一个,一个新的)
我的模型可能是这样的:
class Argument < ApplicationRecord
belongs_to :argumentation
has_one :argumentation
end
class Argumentation < ApplicationRecord
belongs_to :argument
has_many :arguments
end
这里一个例子,我多么希望它应该工作:
称为“康德”的论证有三个参数“a”,“b”和“c”。
论证“c”有一个名为“形而上学”的论证。
称为“形而上学”的论证有两个论点“d”和“e”。
依此类推。
这是我的问题:
这是联想甚至有可能和推荐?
有没有更好的方法来做到这一点?
答
这种关联是否可能并值得推荐?
是的,这是可能的。你只需要正确设置它。
首先,确保您使用2个不同的关联名称。
class Argument < ApplicationRecord
has_one :argumentation
belongs_to :parent_argumentation, class_name: 'Argumentation'
end
接着,在上述的关联,滑轨预计,在参数表中的parent_argumentation_id
列,以便补充一点。
最后是在论证模型
class Argumentation < ApplicationRecord
belongs_to :argument
has_many :arguments, foreign_key: :parent_argumentation_id
end
申报协会既然你也有一个belongs_to
协会宣布在这里,你需要在你的议论表有一个argument_id
列。
提示:使用inverse_of
为了更容易阅读,使之更有效率,建立了inverse_of
选项。
class Argument < ApplicationRecord
has_one :argumentation, inverse_of: :argument
belongs_to :parent_argumentation, class_name: 'Argumentation', inverse_of: :arguments
end
class Argumentation < ApplicationRecord
belongs_to :argument, inverse_of: :argumentation
has_many :arguments, foreign_key: :parent_argumentation_id, inverse_of: :parent_argumentation
end
答
您不需要编写has_one :argumentation
,因为它已经是一对多的关系。所以你的模型应该看起来像这样。
class Argument < ApplicationRecord
belongs_to :argumentation
end
class Argumentation < ApplicationRecord
has_many :arguments
end
这意味着每个参数只会有一个参数。这就是一对多关系的作用。所有参数将只有一个它所属的argumention_id
。
我不确定,如果你看到,我要做什么:每个参数都可以有一个论证(另一个论点,不同于父项)。 – Metaphysiker
对不起,我误解了你的问题。 –