3

想象一下场景:

我有一堂课,有不同类型的学生。所有学生都有相似的属性,但每种类型的学生也有独特的属性。所以我使用 MTI 来保留表学生的共同属性和各自表中的个人属性,并在从班级角度处理学生类型时使用多态性来抽象学生类型。我遵循了本教程:http ://techspry.com/ruby_and_rails/multiple-table-inheritance-in-rails-3/ 。

从这里,我得到了这些模型:

class Clazz < ActiveRecord::Base
  has_many :students
end

class Student < ActiveRecord::Base
  belongs_to :stu, :polymorphic => true
  belongs_to :clazz
end

class Student1 < ActiveRecord::Base
  has_one :student, :as => :stu
end

class Student2 < ActiveRecord::Base
  has_one :student, :as => :stu
end

当我想实例化一个特定的学生(通过学生与班级间接关联)时,我的问题就出现了。我不能在课堂上做到这一点,因为它与特定学生没有联系,当我尝试直接实例化它时,它说它无法识别 ':class' 字段。

Student1.new(:clazz => @clazz, ... [other atributes]...)

unknown attribute: :class

谁能给我一个关于如何做到这一点的提示?Tks

4

2 回答 2

1

在此处查看解决方案:http: //mediumexposure.com/multiple-table-inheritance-active-record/

这类似于 http://techspry.com/ruby_and_rails/multiple-table-inheritance-in-rails-3/

但根据我的经验,前者更好。一方面,它实现了method_missing,后者没有。

于 2012-07-31T10:03:11.773 回答
1

基本上@Aaron 试图问的是这个工作:

class Student < ...
  belongs_to :clazz
end

class Student1 < ...
  has_one :student, :as => :stu

  accepts_nested_attributes_for :stu
end

Student1.new(:stu => {:clazz => @clazz},...[other attributes])

默认情况下,当您需要像这样跨对象树进行初始化时,ActiveRecord 对您没有任何帮助。

于 2011-06-07T20:55:19.357 回答