说我有一个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
方法remove_whitespace
;有没有更好的方法来迭代所有字段,使用块和迭代器去除它们而不是分别键入每个字段(self.username.strip!
)?我班上有大约15个领域,正在寻找一个优雅的解决方案。
答案 0 :(得分:8)
是否有attributes
方法?
attributes.each {|attr| attr.strip!}
或
attributes.each do |attr_name, value|
write_attribute(attr_name, value.strip)
end