And*_*rew 7 ruby activerecord model ruby-on-rails ruby-on-rails-3
我对rails非常陌生,正在开发一个带有Profile模型的Rails 3应用程序.
在配置文件模型中,我想要一个"名称"条目,我希望能够使用简单的语法访问它的逻辑变体:
user.profile.name = "John Doe"
user.profile.name.first = "John"
user.profile.name.last = "Doe"
Run Code Online (Sandbox Code Playgroud)
这是可能的,还是我需要坚持使用"first_name"和"last_name"作为此模型中的字段?
Mis*_*cha 16
这是可能的,但我不推荐它.
我只想坚持first_name和last_name如果我是你,并添加一个方法fullname:
def fullname
"#{first_name} #{last_name}"
end
Run Code Online (Sandbox Code Playgroud)
如果你真的想要 user.profile.name,你可以创建一个Name这样的模型:
class Name < ActiveRecord::Base
belongs_to :profile
def to_s
"#{first} #{last}"
end
end
Run Code Online (Sandbox Code Playgroud)
这允许你这样做:
user.profile.name.to_s # John Doe
user.profile.name.first # John
user.profile.name.last # Doe
Run Code Online (Sandbox Code Playgroud)
其他答案都是正确的,因为他们忽略了#composed_of聚合器:
class Name
attr_reader :first, :last
def initialize(first_name, last_name)
@first, @last = first_name, last_name
end
def full_name
[@first, @last].reject(&:blank?).join(" ")
end
def to_s
full_name
end
end
class Profile < ActiveRecord::Base
composed_of :name, :mapping => %w(first_name last_name)
end
# Rails console prompt
> profile = Profile.new(:name => Name.new("Francois", "Beausoleil"))
> profile.save!
> profile = Profile.find_by_first_name("Francois")
> profile.name.first
"Francois"
Run Code Online (Sandbox Code Playgroud)
如#composed_of页面所述,您必须分配聚合器的新实例:您不能只替换聚合器中的值.聚合器类充当值,就像一个简单的字符串或数字.
我昨天也发了一个回复,答案非常相似:如何最好地将地址与铁轨中的多个模型相关联?