2011-06-07 52 views
2

想象一下場景:帶多態的Rails MTI

我有一個班有不同類型的學生。所有學生都有類似的屬性,但每種類型的學生也有獨特的屬性。因此,我使用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

+0

它給你一個錯誤'unknown attribute:class'還是它說'unknown attribute:clazz'? – 2011-06-07 19:59:45

+0

它說未知屬性:clazz。我很抱歉打字錯誤.. – andre 2011-06-09 07:21:26

回答

0

基本上什麼@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的默認不給你帶來任何好處。