迭代所有mongoid字段的最佳方法

时间:2012-10-05 23:55:50

标签: ruby validation mongodb mongoid sanitization

说我有一个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个领域,正在寻找一个优雅的解决方案。

1 个答案:

答案 0 :(得分:8)

是否有attributes方法?

attributes.each {|attr| attr.strip!}

attributes.each do |attr_name, value|
  write_attribute(attr_name, value.strip)
end