每个人都应该设置首字母字段,但是在创建时设置。
class Person
include MongoMapper::Document
key :first_name, String, required:true
key :last_name, String, required:true
key :initials, String, required:true
timestamps!
before_create :create_initials
def create_initials
@initals = @first_name[0] + @last_name[0]
end
end
Person.create!( first_name: 'Joe', last_name: 'Brown' )
显然这会失败,因为模型在调用前过滤器之前已经过验证。
检查AR Validations表明情况就是这样。但是,使用before_save
过滤器也会失败。
在MongoMapper中创建时设置必填字段的好方法是什么?
答案 0 :(得分:1)
尝试使用after_initialize
class Person
include MongoMapper::Document
key :first_name, String, required:true
key :last_name, String, required:true
key :initials, String, required:true
timestamps!
after_initialize :create_initials
def create_initials
@initals = @first_name[0] + @last_name[0]
end
end