【问题标题】:best way to iterate over all mongoid fields迭代所有 mongoid 字段的最佳方法
【发布时间】:2012-09-27 03:42:15
【问题描述】:

假设我有一个 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 个字段,并且正在寻找一个优雅的解决方案。

【问题讨论】:

    标签: ruby validation mongodb mongoid sanitization


    【解决方案1】:

    没有attributes方法吗?

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

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

    【讨论】:

      猜你喜欢
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2012-02-03
      • 1970-01-01
      • 2021-08-31
      • 2020-10-05
      相关资源
      最近更新 更多