微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – Rails模型:名称 – 第一个,最后一个

我对rails非常陌生,使用适用于用户的Profile模型的Rails 3应用程序.

配置文件模型中,我希望有一个名称”条目,我希望能够使用简单的语法访问它的逻辑变体:

user.profile.name = "John Doe"
user.profile.name.first = "John"
user.profile.name.last = "Doe"

这是可能的,还是我需要坚持使用“first_name”和“last_name”作为此模型中的字段?

解决方法

这是可能的,但我不推荐它.

如果我是你并且添加方法fullname,我会坚持使用first_name和last_name:

def fullname
  "#{first_name} #{last_name}"
end

编辑:

如果你真的想要user.profile.name,你可以像这样创建一个Name模型:

class Name < ActiveRecord::Base
  belongs_to :profile

  def to_s
    "#{first} #{last}"
  end
end

这允许你这样做:

user.profile.name.to_s  # John Doe
user.profile.name.first # John
user.profile.name.last  # Doe

原文地址:https://www.jb51.cc/ruby/269267.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐