2013-03-07 57 views
0

我使用單表繼承在我的應用程序和運行合適的班級爲構建繼承用戶從一個祖先的問題。舉例來說,有以下設置:的ActiveRecord不會建使用STI

class School < ActiveRecord::Base 

    has_many :users 

end 

class User < ActiveRecord::Base 


    attr_accessible :type #etc... 

    belongs_to :school 

end 

Class Instructor < User 

    attr_accessible :terms_of_service 
    validates :terms_of_service, :acceptance => true 

end 


Class Student < User 

end 

如何建立無論是從學校實例的instructorstudent記錄?試圖像School.first.instructors.build(....)只給了我一個新的用戶實例,並生成特定講師表單時,我不會有機會獲得教練的具體領域,如terms_of_service導致錯誤後向下騎,從控制檯構建會給我一個大規模分配錯誤(因爲它試圖創建一個用戶記錄,而不是一個導師記錄作爲指定)。我給的例子學校,但也有我想從用戶表繼承,所以我不必重複碼或字段在數據庫中的一些其他協會。我是否有這個問題,因爲不能在STI設置中共享關聯?

+0

協會在STI的關係被共享,但學校不知道的是,你必須實現學校新的一個將在未來的答案。 – 2013-03-07 21:31:50

+0

試過,我是否必須添加任何額外的字段到數據庫中才能使這種方法起作用? (這樣會打敗STI的目的) – Noz 2013-03-07 21:38:33

+0

不,只需正確設置STI:使用字段'type'數據類型字符串重新加載環境。它應該工作。如果沒有,請提供更多的代碼讓我們瞭解錯誤。 – 2013-03-07 21:41:05

回答

0

OK似乎是問題的一部分,從有我學校模型內的老users協會朵朵。刪除並添加協會的學生和教師個人工作。

更新School.rb

class School < ActiveRecord::Base 

    #removed: 
    #has_many :users this line was causing problems 

    #added 
    has_many :instructors 
    has_many :students 

end 
1

應指定導師明確

class School < ActiveRecord::Base 

    has_many :users 
    has_many :instructors,:class_name => 'Instructor', :foreign_key => 'user_id' 

end 
+0

沒有工作,我添加了代碼,跑'School.last.instructors.build(:TERMS_OF_SERVICE =>真)',並得到,因爲它仍然認爲這是一個用戶記錄的質量分配錯誤。 – Noz 2013-03-07 21:29:59

+0

@Cyle嘗試在構建時指定類型 'School.first.instructors.build(type:'Instructor')' – 2013-03-07 21:38:07

+0

@Cyle您還可以嘗試說 'user = School.first.instructors.build(... ); user.becomes('Instructor')' – 2013-03-07 21:42:18

1

還有呢:

class School < ActiveRecord::Base 
    has_many :users 
    has_many :instructors 
end 

class Instructor < User 
    attr_accessible :terms_of_service # let it be at the first place. :) 

    validates :terms_of_service, :acceptance => true 
end 
+0

謝謝你的建議 – Noz 2013-03-07 21:53:17