在设计用户模型中创建 FullName 方法?

发布于 2024-11-16 02:47:02 字数 219 浏览 2 评论 0原文

现在我使用 devise 并有两个字段。 fname 和 lname。

我希望能够将 full_name 字段放入用户模型中。然后,用户模型将采用 full_name 字段并通过用空格分隔来提取 fname 和 lname。如果有多个空格,则全部转到 fname,最后一项将是姓氏,然后使用提取的 fname 和 lname 字段保存到用户模型。

无需破解设备这可能吗?

谢谢

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 possible without hacking up devise?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一杆小烟枪 2024-11-23 02:47:02

当前两个答案的问题在于它们不处理三个(+)单词名称,例如比利·鲍勃·松顿(Billy Bob Thornton)。

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

原始帖子要求除姓氏之外的所有内容都改为名字。所以我建议:

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

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
风透绣罗衣 2024-11-23 02:47:02

你不需要破解设计本身,只需在你的用户模型中进行即可(或者你使用的任何模式作为你的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

未经测试的并且超出了我的想象,但这应该是一个开始。 ...

我不建议存储全名,只需将其用作辅助函数,但这取决于您。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文