虽然我认为 STI 可能是我会使用的方法,但如果您想避免大量NULL属性,另一种可能性是在您的 Person 模型中添加一个列other_attributes来存储一个Hash属性。为此,请text向表中添加一列people:
def self.up
add_column :people, :other_attributes, :text
end
然后确保该属性在模型中被序列化。您可能需要编写一个包装器以确保Hash在使用它时将其初始化为空:
class Person < ActiveRecord::Base
serialize :other_attributes
...
def other_attributes
write_attribute(:other_attributes, {}) unless read_attribute(:other_attributes)
read_attribute(:other_attributes)
end
end
然后您可以按如下方式使用该属性:
p = Person.new(...)
p.other_attributes #=> {}
pl = Player.new(...)
pl.other_attributes["position"] = "forward"
pl.other_attributes #=> {"position" => "forward"}
这种方法的一个警告是,在从 中检索数据时,您应该使用字符串作为键,因为从数据库中检索other_attributes时,键将始终是字符串。Hash