自联接类的正确活动记录关联



我一直在修改一个在线 Rails 教程以满足我的特定需求,我发现自己已经超出了我的深度。一点澄清将不胜感激。我的代码在我的问题下面。

此时,如果danrob是类User的实例,我调用

dan.add_supervisor(rob)

然后它返回一个空集合:

dan.supervisors
=> #<ActiveRecord::Associations::CollectionProxy []>

然而,监督本身已经创建:

dan.initiated_supervisions
=> #<ActiveRecord::Associations::CollectionProxy [#<Supervision id: 50, supervisor_id: 68, supervisee_id: 67, created_at: "2015-03-10 18:30:01", updated_at: "2015-03-10 18:30:01">]>

理想的行为是让has_many :through行为正常工作,并且能够通过调用 dan.supervisors 来获取 Dan 的主管列表。我需要进行哪些更改才能实现这一点?

用户.rb

...
# Supervisees can choose their supervisors, 
# but not the other way around.
has_many :initiated_supervisions,     class_name: "Supervision", 
                                      foreign_key: "supervisee_id", 
                                      dependent: :destroy
has_many :non_initiated_supervisions, class_name: "Supervision", 
                                      foreign_key: "supervisor_id", 
                                      dependent: :destroy
has_many :supervisees, through: :non_initiated_supervisions
has_many :supervisors, through: :initiated_supervisions
...
def add_supervisor(other_user)
  initiated_supervisions.create(supervisor_id: other_user.id)
end
...

监督.rb

...
belongs_to :supervisor,    class_name: "User"
belongs_to :supervisee,    class_name: "User"
validates  :supervisor_id, presence:   true
validates  :supervisee_id, presence:   true
...

解决方案(暂时...拜托,哦,请继续工作...在两个User模型关联中指定class_name: "User"

has_many :supervisors, through: :initiated_supervisions, class_name: "User"
has_many :supervisees, through: :non_initiated_supervisions, class_name: "User"

最新更新