Rails3 / Mongoid - 将模型保存为小写

时间:2011-10-18 19:42:55

标签: ruby-on-rails-3 mongoid

我正在使用Rails 3.1和Mongoid。什么是强制我的模型字段保存为小写的正确方法?我没有在Mongoid文档中看到这个,但我想知道是否有一种我应该知道的清洁方式。非常感谢。

3 个答案:

答案 0 :(得分:3)

好的,所以我更全面地阅读了文档,我最初应该这样做。这对我来说很有用。

在model.rb中:

...
before_create :drop_the_case

protected
def drop_the_case
  self.MYMODELFIELD = self.MYMODELFIELD.downcase
end

“drop_the_case”是我自己的任意名称。

感谢。

答案 1 :(得分:1)

在您的模型中,您可以使用

def before_save
  self.your_model_field = your_model_field.downcase
end

def before_save
    self.your_model_field.downcase!
end

看看http://www.ruby-forum.com/topic/109091这应该有用!!

答案 2 :(得分:1)

before_create回调的已接受答案存在一些重大问题,特别是如果您使用某些约束,例如validates_uniqueness_of。如果可能,请使用before_validation回调。

class Safe
    include Mongoid::Document
    field :foo, type: String

    validates_uniqueness_of :foo

    before_validation :drop_the_case

    protected
    def drop_the_case
        self.foo = self.foo.downcase
    end
end

class Dangerous
    include Mongoid::Document
    field :foo, type: String

    validates_uniqueness_of :foo

    before_create :drop_the_case

    protected
    def drop_the_case
        self.foo = self.foo.downcase
    end
end

dangerous = Dangerous.create!(name: 'BAR')
safe = Safe.create!(name: 'BAR')

dangerous.update(name: 'BAR') # dangerous.name => BAR
safe.update(name: 'BAR') # safe.name => bar

Dangerous.create!(name: 'BAR') # => true, unique constraint ignored
Safe.create!(name: 'BAR') # throws exception