在这样的情况下,创建活动记录关系的正确方法是什么-
模型A的一个实例可以同时属于另外两个模型的多个实例,即模型B和模型C。
B型只能有一个A型。
C型可以有很多A型。
一个例子是一个招聘委员会,雇主正在招聘一个职位,而应聘者正在申请,并且有许多以前的职位。我希望候选人和雇主的职位来自同一个模式。
职位模式(模式A)可以同时属于雇主和应聘者
雇主模式(B型) has_one职位
候选模型(C型) has_many职位
发布于 2016-11-15 21:16:23
以下是完成问题中所描述的内容的一种方法:
class Position < ActiveRecord::Base
belongs_to :candidate
belongs_to :employer
end
class Employer < ActiveRecord::Base
has_many :positions
end
class Candidate < ActiveRecord::Base
has_many :positions
ens请注意,一个职位一次只能属于一个雇主和一个候选人;如果您正在创建一个招聘板,这是一种荒谬的做法--职位和雇主之间的关系可能是正确的,但应聘者可能有许多申请,而一个应用程序将belong_to一个职位,而一个职位has_many应用程序。或者也可能是“最爱”,这样候选人就可以跟踪要申请的职位列表。
您开始使用的“理论”示例:
代码:
class ModelA < ActiveRecord::Base
has_many :model_bs
has_many :model_c_relationships # join table!
has_many :model_cs, through: :model_c_relationships
end
class ModelB < ActiveRecord::Base
belongs_to :model_a
end
class ModelCRelationship < ActiveRecord::Base
belongs_to :model_a
belongs_to :model_c
end
class ModelC < ActiveRecord::Base
has_many :model_c_relationships
has_many :model_as, through: :model_c_relationships
end如果有一种情况,一种类型的对象可以属于另一种对象,而另一种对象可以是几种类型中的一种,那么它可能需要一个多态关联。例如,StackOverflow允许您同时评论问题和答案。注释只能属于一个可注释的父对象,因此代码可能如下所示:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
class Question < ActiveRecord::Base
has_many :comments, as: :commentable
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
has_many :comments, as: :commentable
endhttps://stackoverflow.com/questions/40617120
复制相似问题