我有一個名爲Person的Rails模型,它具有first_name和last_name的數據庫表列。我還定義了一個full_name方法來返回實例的組合first_name和last_name。如何返回通過Rails模型方法定義的屬性數組以及數據庫表中的屬性?
有沒有辦法返回一個數組,哈希,或具有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
返回一個哈希數組,其中也包括full_name。
感謝先進!
謝謝,但有沒有辦法在一個散列內返回所有三個:first_name,last_name和full_name?當我嘗試你的代碼時,你的兩個例子都沒有。 – Chanpory 2010-11-10 00:02:58
你是什麼意思的一個散列?擴展您的問題以包含預期結果。 – 2010-11-10 00:06:25
請查看問題中的第三個例子:'#'...返回first_name,last_name和full_name。 –
Chanpory
2010-11-10 00:07:53