2

我有以下类与 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")

我想阻止为员工设置大学领域,但允许为 StudentEmployees 设置。我尝试使用 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

这里的问题是它将在数据库中插入一所简单员工的大学。另一个问题是,我认为最好在 StudentEmployee 类中说大学是一个属性,而不是在 Employee 中说大学“不是”一个可见属性......它只是逆向自然抽象。

谢谢。

4

1 回答 1

2

我会尝试这样的事情:

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

它不是最漂亮的,但它应该可以工作。

于 2012-10-24T01:39:05.103 回答