0

如果用戶 - >學生//員工(單表繼承),並且他們都屬於組織 - >學校//工作(單表繼承),那麼編寫關聯的正確方法是什麼?我將organization_id放入User類,並在相應的子類中寫入屬於/有許多,但是當我調用User.school時,即使他的organization_id = 1,我也會得到「nil」。我們的Rails建模思路出了什麼問題?

user .RB

class User < ActiveRecord::Base 
    attr_accessible :email, :name, :password, :organization_id, :type 
end 

student.rb

class Student < User 
    belongs_to :school 
end 

employee.rb

class Employee < User 
    belongs_to :company 
end 

組織。 RB

class Organization < ActiveRecord::Base 
    attr_accessible :name 
end 

school.rb

class School < Organization 
    has_many :students 
end 

company.rb

class Company < Organization 
    has_many :employees 
end 

回答

0

我會強烈建議你不要使用單表繼承。你從中得到什麼好處?學生和員工是不同的,學校和公司也是如此。他們應該是單獨的表格。它會使你的生活如此簡單,長遠來看也是如此。如果你不使用單表繼承,這個問題也會消失。

0

User類未定義學校關聯,並且完全不瞭解Student類。所以你不能指望User.school工作。你可以期待Student.school的工作,因爲這是你的代碼定義。

STI形成柱的視角,它只是添加一個類型字符串列,它顯示記錄映射到哪個模型的子類型。

您也可能會重新考慮如何爲數據建模。一個學生屬於一所學校,但一個用戶也可能屬於一家公司或兩所學校。