Rails: Combining last name and first name in Rails model
FIN开发者_开发百科AL SOLUTION:
I have a Rails 3 app that uses Devise to handle authentication. In the signup form i have the following fields:
<p><%= f.label :first_name %><br />
<%= f.text_field :first_name %></p>
<p><%= f.label :last_name %><br />
<%= f.text_field :last_name %></p>
I need to capitalize first and last names and combine them in the User model in a database field called 'login' (e.g. Lastname, Firstname). Here is the complete user model:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :remember_me, :login
validates :first_name, :last_name, :email, :password, :password_confirmation, :presence => true
before_create :create_login
def create_login
self.login = "#{last_name.capitalize}, #{first_name.capitalize}"
end
end
Thanks.
I genuinely, honestly, and truly applaud your use of the power of Ruby, but since this is such a straightforward and static concatenation of two strings, I'd go with:
def create_login
login = "#{last_name.capitalize}, #{first_name.capitalize}"
end
As for the nil:NilClass
issue, are you adding first_name and last_name columns to your users table in your associated migration?
before_create :create_login
validates :first_name, :presence => true
validates :last_name, :presence => true
def create_login
login = [last_name, first_name].map(&:capitalize).join(", ")
end
Short explanation
I think it is good to get first_name
and last_name
on registration: so we will ad validation to it. Also it is good idea to validate length and match it with some regexp.
Then, as far as login is creates only once, we will add before_create
callback, which will be executed only when object is creating (not updating). before_create
callback will be run only if validation is passed, so if first_name
or last_name
is blank - validation won't be passed and callback won't be executed till first_name
and last_name
is filled.
UPD
Ok, as far as you get your error:
def create_login
login = [last_name, first_name].compact.map(&:capitalize).join(", ")
end
精彩评论