Easy way to always make lowercase letters in db

I am currently doing the following in a model:

before_save :to_lower before_create :to_lower def to_lower self.name = self.name.downcase end 

Seems pretty repetitive to me.

+6
source share
4 answers

You do not need the before_create command if you already have before_save.

 before_save { |user| user.name = user.name.downcase } 
+15
source

I usually handle cases like this:

 def name= name super(name.try(:downcase)) end 
+3
source
 def name=(val) write_attribute(:name, val.downcase) end 
+1
source

Why are you doing this? If it performs a case-insensitive search, you can simply put it in your query logic (in fact, I think Rails does this a bit already). However, if you really want the data to be lowercase normalized in the database (say, if you are dealing with SHA1 hashes or something else), then you are doing the right thing.

0
source

Source: https://habr.com/ru/post/901305/


All Articles