【发布时间】:2010-11-09 23:42:19
【问题描述】:
我有一个名为 Person 的 Rails 模型,其中包含 first_name 和 last_name 的数据库表列。我还定义了一个 full_name 方法来返回实例的组合 first_name 和 last_name。
有没有办法返回包含 first_name、last_name 和 full_name 的数组、散列或对象?
这是我的代码:
#person.rb
class Person < ActiveRecord::Base
validates_presence_of :first_name, :last_name
def full_name
self.first_name + " " + self.last_name
end
end
这是我在 Rails 控制台中尝试过的:
ruby-1.8.7-p302 > person = Person.new({:first_name=>"Bruce", :last_name=>"Wayne"})
=> #<Person id: nil, first_name: "Bruce", :last_name: "Wayne", created_at: nil, updated_at: nil>
ruby-1.8.7-p302 > person.save!
=> true
ruby-1.8.7-p302 > Person.last
=> #<Person id: 1, first_name: "Bruce", :last_name: "Wayne", created_at: "2010-11-09 22:53:14", updated_at: "2010-11-09 22:53:14">
是否有可能得到像这样返回的东西:
ruby-1.8.7-p302 > Person.last
=> #<Person id: 1, first_name: "Bruce", :last_name: "Wayne", :full_name: "Bruce Wayne", created_at: "2010-11-09 22:53:14", updated_at: "2010-11-09 22:53:14">
还是只能从数据库返回值?
最后,我希望能够调用Person.all 来返回一个哈希数组,其中还包括全名。
提前致谢!
【问题讨论】:
标签: ruby-on-rails arrays attributes instance