Hopstream
Hopstream

Reputation: 6451

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.

Upvotes: 7

Views: 6385

Answers (4)

rakesh kumar
rakesh kumar

Reputation: 97

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

Upvotes: 1

rubish
rubish

Reputation: 10907

I generally handle such cases by:

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

Upvotes: 3

Marnen Laibow-Koser
Marnen Laibow-Koser

Reputation: 6337

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.

Upvotes: 0

kain
kain

Reputation: 5570

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

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

Upvotes: 16

Related Questions