Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to always make a field lowercase in db

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.

like image 930
Hopstream Avatar asked Nov 11 '11 16:11

Hopstream


2 Answers

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

before_save { |user| user.name = user.name.downcase }
like image 109
kain Avatar answered Oct 07 '22 13:10

kain


I generally handle such cases by:

def name= name
  super(name.try(:downcase))
end
like image 40
rubish Avatar answered Oct 07 '22 11:10

rubish