2012-10-05 46 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 
相關問題