2017-01-11 52 views
-1

我需要獲取對象的所有屬性。我知道有一個方法attributes,但它不會返回爲零的屬性。 例如:如何獲取對象的所有屬性,包括那些零?

class User 
    include Mongoid::Document 

    field :name 
    field :email 
    field :age 
end 

u = User.new(email: '[email protected]', name: 'foo') 
u.save 
u.attributes # {'email' => '[email protected]', 'name' => 'foo'} 

我需要u.attributes返回{'email' => '[email protected]', 'name' => 'foo' 'age' => nil}

有一個方法as_json這我想要做什麼,但它是慢了很多。速度非常重要。

回答

0

我找到了一個快速的解決方案

self.attribute_names.map { |name| [name, self[name]] }.to_h 

它所有我想要=)

相關問題