Reputation: 7583
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
?
Upvotes: 1
Views: 189
Reputation: 3488
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: "[email protected]"
u.user_name # => "email_is: [email protected]"
Upvotes: 1
Reputation: 370
In your model:-
before_create :add_user_name
private
def add_user_name
self.user_name = self.email
end
Upvotes: 2