Search code examples
ruby-on-railsdevise

Devise: Capitalize First Name


I added a new field in devise called firstname, and I want it to be capitalized by devise during registration.

I first ran: rails generate migration add_username_to_users firstname:string

then

rake db:migrate

After that I added firstname to the configure_permitted_parameters in the application_controller.rb and updated the views. I basically used this but stripped out some unnecessary stuff.

I dont know where I should put the code for capitalizing the firstname and lastname (as well as some other validating). Any guidance would be appreciated. Thanks.


Solution

  • I think you should put capitalization of first and last names in your User model. Every time a user is saved, you can capitalize the first and last name. In addition, all validation (or attribute pre-processing/sanitization) can be done at the model level as well.

    class User < ActiveRecord::Base
      before_save :capitalize_names
    
      def capitalize_names
        self.firstname = firstname.camelcase
        self.lastname = lastname.camelcase
      end
    end