问题
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