我用sti映射了以下类:
class Employee < ActiveRecord::Base
end
class StudentEmployee < Employee
# I'd like to keep university only to StudentEmployee...
end
#Just to make this example easier to understand, not using migrations
ActiveRecord::Schema.define do
create_table :employees do |table|
table.column :name, :string
table.column :salary, :integer
table.column :university, :string # Only Students
end
end
emp = Employee.create(:name=>"Joe",:salary=>20000,:university=>"UCLA")
我不想为员工设置大学场地,但允许为学生员工设置。我试图使用attr_protected,但它只能防止质量设置:
class Employee < ActiveRecord::Base
attr_protected :university
end
class StudentEmployee < Employee
attr_accessible :university
end
#This time, UCLA will not be assigned here
emp = Employee.create(:name=>"Joe",:salary=>20000,:university=>"UCLA")
emp.university = "UCLA" # but this will assign university to any student...
emp.save
puts "only Students should have univesities, but this guy has one..."+emp.university.to_s
这里的问题是,它将在数据库中插入一个供简单员工使用的大学。
另一个问题是,我认为最好在学生就业班上说大学是一个属性,而不是在员工身上说大学“不是”一个可见的属性它只是朝着与自然抽象相反的方向发展。
谢谢。
最佳答案
我想试试这样的:
class Employee < ActiveRecord::Base
validate :no_university, unless: lambda { |e| e.type === "StudentEmployee" }
def no_university
errors.add :university, "must be empty" unless university.nil?
end
end
它不是最漂亮的,但应该有用。
关于ruby - Ruby 3上的activerecord单表继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13032204/