Simple way to always make a field lowercase in db

眉间皱痕 提交于 2019-12-22 05:11:49

问题


Currently I'm doing the following in the model:

before_save :to_lower
before_create :to_lower

def to_lower
  self.name = self.name.downcase
end

Seems pretty repetitive to me.


回答1:


You don't need the before_create if you already have before_save.

before_save { |user| user.name = user.name.downcase }



回答2:


I generally handle such cases by:

def name= name
  super(name.try(:downcase))
end



回答3:


def name=(val)
  write_attribute(:name, val.downcase)
end



回答4:


Why are you doing this? If it's to perform case-insensitive searches, you might just want to put that into your query logic (actually, I think Rails does a bit of that already). However, if you actually want the data normalized to lowercase in the DB (say, if you're dealing with SHA1 hashes or something), then you're doing the right thing.



来源:https://stackoverflow.com/questions/8096673/simple-way-to-always-make-a-field-lowercase-in-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!