1

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?

rails_id
  • 8,120
  • 4
  • 46
  • 84
AZ.
  • 7,333
  • 6
  • 44
  • 62

2 Answers2

2

In your model:-

before_create :add_user_name

private
  def add_user_name
    self.user_name = self.email
  end
Nikita Singh
  • 370
  • 3
  • 12
1

Use default:

class User
 include Mongoid::Document
 field :email, type: String
 field :user_name, default: ->{ "email_is: #{email}" }
end

"If you want to set a default with a dependency on the document's state, self inside a lambda or proc evaluates to the document instance."

See: Mongoid fields documentation

Tested with rails c:

u = User.new email: "name@domain.com"
u.user_name # => "email_is: name@domain.com" 
Enrique Fueyo
  • 3,358
  • 1
  • 16
  • 10
  • No need to use self. self.email or email will do the work. Besides this will work even with users created in the database before the default user_name was implemented. – Enrique Fueyo Oct 15 '13 at 09:32
  • It throws error if not using `self.email` when create the user in rails console. – AZ. Oct 16 '13 at 02:21
  • Which rails/mongoid versions are you using. It works for me tested with ruby 1.9.3, rails 3.2.0 and mongoid 3.1.5 – Enrique Fueyo Oct 16 '13 at 14:11