Search code examples
ruby-on-railsruby-on-rails-3mongoidmongoid3

How to initialize field based on another field?


I have a user model with :email and :user_name, I want to auto initialize :user_name with part of :email.

class User
  include Mongoid::Document
  field :email
  field :user_name
end

I use simple_form to create the user. How can I initialize :user_name based on :email?


Solution

  • In your model:-

    before_create :add_user_name
    
    private
      def add_user_name
        self.user_name = self.email
      end