Ruby on Rails - Can I modify data before it is saved?
Quick example: A user enters a username into a form, and I need to make that text username before storing it in the app's database, thereby making it permanently lowercase.
Where would I put this code, and how would I access the data to be lowercased?
Thanks.
you should overwrite the attribute writer:
class User < ActiveRecord::Base
def username=(val)
write_attribute(:username, val.downcase)
end
end
You could use one of ActiveRecords callbacks in your User model, eg something like that:
before_save { |user| user.username = user.username.downcase }
In your User model (models/user.rb), take advantage of ActiveRecord callbacks:
before_save do
self.username = self.username.downcase
end