我一直在修改在线Rails教程以满足我的特定需求,而且我已经发现自己超出了我的深度。一点点清晰度将非常感激。我的代码低于我的问题。
此时,dan
和rob
是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的主管列表。为实现这一目标,我需要做出哪些改变?
User.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
...
Supervision.rb
...
belongs_to :supervisor, class_name: "User"
belongs_to :supervisee, class_name: "User"
validates :supervisor_id, presence: true
validates :supervisee_id, presence: true
...
答案 0 :(得分:0)
解决方案(暂时......请,请继续工作......)在两个class_name: "User"
模型关联中指定User
:
has_many :supervisors, through: :initiated_supervisions, class_name: "User"
has_many :supervisees, through: :non_initiated_supervisions, class_name: "User"