【问题标题】:Rails self-referential has_many throughRails 通过自引用 has_many
【发布时间】:2011-03-02 09:54:10
【问题描述】:

我正在尝试创建一个具有三种基本用户类型的自引用用户类——家长、学生和导师。学生属于父母,也可以属于导师。当然,按照我写的方式,rails 只识别有学生的父母。如果用户是导师,则 User.students 总是返回空,但当用户是父母时它可以工作。有什么想法吗?

class User < ActiveRecord::Base
# Sets up the tutor has_many students assocation
has_many :tutees, :foreign_key=>"tutor_id",
                :class_name=>"Relationship"
has_many :students, :through=>:tutees

# Sets up the student has_many tutors association
has_many :mentors, :foreign_key=>"student_id",
                 :class_name=>"Relationship"
has_many :tutors, :through=>:mentors

# Sets up the parent has_many students assocation
has_many :children, :foreign_key=>"parent_id",
                  :class_name=>"Relationship"
has_many :students, :through=>:children

# Sets up the student has_many parents 
has_many :mommies, :foreign_key=>"student_id",
                 :class_name=>"Relationship"
has_many :parents, :through=>:mommies

关系类:

class Relationship < ActiveRecord::Base
 belongs_to :tutor, :class_name=>"User"
 belongs_to :student, :class_name=>"User"
 belongs_to :parent, :class_name=>"User"
end

这些部分(家长、学生、导师)也是各自的班级。基本用户信息在 User 类中,而特定于导师的数据在 Tutor 类中。

【问题讨论】:

  • 你的Relationship 班级是什么样的?
  • 我假设您问题中的每个部分也属于不同的类别,对吧?
  • 贴出关系码。是的,每个部分(家长、学生、导师)也有自己的班级。

标签: ruby-on-rails ruby-on-rails-3 has-many-through has-many-polymorphs


【解决方案1】:

这是因为同名(学生)的关系。

在你的情况下, has_many :students, :through=>:tutees 覆盖 has_many :students, :through=>:children 关系。

所以你需要使用不同的名称才能工作。

-阿什

【讨论】:

  • 是的,我想你是对的。我将 :students 重命名为 :students_tutored。唯一的窍门是我还必须命名 :source。所以解决方案看起来像 has_many :students_tutored, :through=>:tutees, :source=>:student
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
相关资源
最近更新 更多