2012-10-05 41 views
1

说我有一个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 

在该方法中remove_whitespace;有没有更好的方法来遍历所有的领域去剥离他们使用块和迭代器,而不是分别键入每个字段(self.username.strip!)?我在班上有大约十五个领域,并正在寻找一个优雅的解决方案。

回答

7

是不是有attributes方法?

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

attributes.each do |attr_name, value| 
    write_attribute(attr_name, value.strip) 
end 
相关问题