Lor*_*ing 1 ruby validation sanitization mongodb mongoid
说我有一个mongoid类
Class User
include Mongoid::Document
field :username, type: String
field :age, type: Integer
before_save :remove_whitespace
def remove_whitespace
self.username.strip!
self.age.strip!
end
end
Run Code Online (Sandbox Code Playgroud)
在方法中remove_whitespace; 有没有更好的方法迭代所有字段使用块和迭代器去除它们而不是单独键入每个字段(self.username.strip!)?我班上有大约15个领域,正在寻找一个优雅的解决方案.
不是有attributes方法吗?
attributes.each {|attr| attr.strip!}
Run Code Online (Sandbox Code Playgroud)
要么
attributes.each do |attr_name, value|
write_attribute(attr_name, value.strip)
end
Run Code Online (Sandbox Code Playgroud)