2

I have a User model that's used to hold all Users. There's two types on users in my apps, mentors and students, but they have the same structure.

I want to do something like this.

has_many :requests, :foreign_key => mentor? ? 'mentor_id' : 'student_id', :class_name => 'Request'

I have the mentor? method in the model but it gives me a method_missing error. I'm assuming it's because it's looking for the method in dynamic_matchers.rb

This is the error it gives

/var/lib/gems/1.9.1/gems/activerecord-3.2.13/lib/active_record/dynamic_matchers.rb:55:in 'method_missing': undefined method 'mentor?' for #<Class:0x00000001b40630> (NoMethodError)

Is there a way to go about this without making a seperate models for the Student and Mentor? I feel that'd it be unnecessary seeing that they both use the same fields.

4

2 回答 2

5

好的,让我更正一下:这是不可能的,即使在乌托邦世界中是这样,或者您找到了解决方法,这肯定是不正确的。

实际上,您正在寻找的是继承(STI 或 Rails 中的单表继承)和多态性之间的混合。

您如何以正确的方式实现这一点?

你有一个用户模型,学生导师都是用户,所以他们都会继承这个模型。

class User < ActiveRecord::Base
end

class Student < User
end

class Mentor < User
end

它意味着什么?好吧,这意味着 User 模型拥有(无需您做任何其他事情)一个字段类型,该字段类型将包含“Student”或“Mentor”或不包含任何内容,具体取决于您初始化对象的方式:

user = User.create()
student = Student.create()
mentor = Mentor.create()

现在,您的Request可以属于StudentMentor。所以在这里你可以像这样设置一个多态关联:

class Student < User
  has_many :requests, as: :owner
end

class Mentor < User
  has_many :requests, as: :owner
end

class Request < ActiveRecord::Base
  belongs_to :owner, polymorphic: true
end

现在你可以写:

student.requests
mentor.requests
request.owner
于 2013-05-12T21:13:48.387 回答
1

我不太确定你需要什么。相同的模型结构,一个用户可以成为多个学生的导师?一个学生可以有一个导师?就是它?

如果是,那么自我加入呢?

class User < ActiveRecord::Base
  has_many :students, :class_name => "User", :foreign_key => "mentor_id"
  belongs_to :mentor, :class_name => "User"
end

这样你就可以调用 student.mentor 和mentor.students

于 2013-05-12T21:12:46.260 回答