开发者

Creating a FullName method in the Devise User Model?

开发者 https://www.devze.com 2023-03-14 01:30 出处:网络
right now I use devise and have two fields. fname and lname. I would like the ability to put a full_name field to the user model. Then the user model would take the full_name field and extract the fn

right now I use devise and have two fields. fname and lname.

I would like the ability to put a full_name field to the user model. Then the user model would take the full_name field and extract the fname and lname by splitting with a space. if there is more than one space that would all go to the fname and the last item would be the last name, and then saved to the user model with the extracted fields for fname and lname.

Is this po开发者_C百科ssible without hacking up devise?

Thanks


The problem with both current answers is that they don't handle three(+) word names such as Billy Bob Thornton.

'Billy Bob Thornton'.split(/(.+) (.+)$/)  => ["", "Billy Bob", "Thornton"] 
'Billy Bob Thornton'.split(' ', 2)        => ["Billy", "Bob Thornton"] 

The original posting requests all but the last name to go to first name. So I'd suggest:

def full_name
  [first_name, last_name].join(' ')
end

def full_name=(name)
  elements = name.split(' ')
  self.last_name = elements.delete(elements.last)
  self.first_name = elements.join(" ")
end


You don't need to hack up devise persay, just do it in your Users model (or whatever modal you are usuing as your devise_for

class User
  def fullname
    self.fname << " " << self.lname
  end
  def fullname=(fname)
    names = fname.split(/(.+) (.+)$/)
    self.fname = names[0]  
    self.lname = names[1] 
  end
end

untested and off the top my head, but it should be a start....

i wouldn't suggest storing the fullname, just use it like a helper function, but that is up to you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号