Ruby on Rails - Can I modify data before it is saved?

Viewed 33477

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.

7 Answers

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 the general case, The submit button on the form should delegate to a controller action where params[:user_name] is available. You could lowercase that before doing a SomeModel.update(params) or create(params).

So you could do it in the controller action.

I would suggest adding an Observer to the model and doing this action in the before_save method. Then it is guaranteed to lowercase the username no matter which controller or action is creating it, and if there is an issue performing any action within the observer, an exception is thrown and the object won't save.

Edit: Please note that you can't do a Model.save within the before_save tied to that model, otherwise you end up in an infinite loop. You'll need to do an update_attributes or something.

Related