Ruby on rails 3 Rails3/Mongoid-将模型保存为小写
我正在使用Rails 3.1和Mongoid。强制将模型的字段保存为小写的正确方法是什么?我在Mongoid文档中没有看到这一点,但我想知道是否有一种干净的方法我应该知道。非常感谢。在您的型号中,您可以使用Ruby on rails 3 Rails3/Mongoid-将模型保存为小写,ruby-on-rails-3,mongoid,Ruby On Rails 3,Mongoid,我正在使用Rails 3.1和Mongoid。强制将模型的字段保存为小写的正确方法是什么?我在Mongoid文档中没有看到这一点,但我想知道是否有一种干净的方法我应该知道。非常感谢。在您的型号中,您可以使用 def before_save self.your_model_field = your_model_field.downcase end 或 看看这个应该有用 在您的模型中,您可以使用 def before_save self.your_model_field = your_mo
def before_save
self.your_model_field = your_model_field.downcase
end
或
看看这个应该有用 在您的模型中,您可以使用
def before_save
self.your_model_field = your_model_field.downcase
end
或
看看这个应该有用 好的,所以我更彻底地阅读了文档,这是我最初应该做的。这对我来说很有用 在model.rb中:
...
before_create :drop_the_case
protected
def drop_the_case
self.MYMODELFIELD = self.MYMODELFIELD.downcase
end
“放下这个案子”是我自己的任意名字
谢谢。好的,所以我更彻底地阅读了文档,这是我最初应该做的。这对我来说很有用 在model.rb中:
...
before_create :drop_the_case
protected
def drop_the_case
self.MYMODELFIELD = self.MYMODELFIELD.downcase
end
“放下这个案子”是我自己的任意名字
谢谢。在创建之前使用
回调的公认答案有一些大问题,特别是如果您使用某些约束,如验证的唯一性。在可能的情况下,使用验证前的回调
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
使用创建之前的回调的可接受答案有一些大问题,特别是当您使用某些约束(如验证的唯一性)时。在可能的情况下,使用验证前的回调
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
您还可以将区分大小写:false添加到唯一性验证中。例如:validates\u university\u of:foo,:case\u sensitive=>false您还可以将case\u sensitive:false添加到唯一性验证中。例如:验证:foo的唯一性,:区分大小写=>false