views:

252

answers:

4

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.

+16  A: 

You could use one of ActiveRecords callbacks in your User model, eg something like that:

before_save { |user| user.username = user.username.downcase }
effkay
More on ActiveRecord callbacks: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
Andreas
A: 

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.

Gishu
You need to think about the consequences of tightly coupling the controller and the model. What happens when two controllers need to create an instance of this model? What about using the console to create a user, and the developer forgets that usernames ought to be downcase? What about unit testing? I think a better approach is to use the ActiveRecord callbacks as suggested by effkay.
Tate Johnson
Yes I upvoted him too. My reasoning : As long as its in one-place I dont really care. it didn't really look like there were multiple places from the OP's question.. so i went for the simplest thing that could possibly work. Also you may not always have a model.. in this scenario however it looks like the OP should be using one.
Gishu
+5  A: 

you should overwrite the attribute writer:

class User < ActiveRecord::Base
  def username=(val)
    write_attribute(:username, val.downcase)
  end
end
Michael Siebert
Yes, this is the better solution. It will ensure consistency even before an object is saved to the database.
molf
A: 

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.

Mike Trpcic