In your model:-
before_create :add_user_name
private
def add_user_name
self.user_name = self.email
end
質問
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
?
解決
In your model:-
before_create :add_user_name
private
def add_user_name
self.user_name = self.email
end
他のヒント
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"