2016-08-17 57 views
5

可以使用column_names來獲取表的所有列,但如果想知道ActiveRecord中特定實例的所有值,該怎麼辦。如何獲取Rails中Active Record中對象的所有值?

例如,

User.column_names 
=> ["id", "email", "encrypted_password", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "tel", "interests", "admin_status", "created_at", "updated_at", "city_id", "profile_image_file_name", "profile_image_content_type", "profile_image_file_size", "profile_image_updated_at"] 

User.first 
=> #<User id: 1, email: "[email protected]", tel: "+923223333333", interests: "Hi, I'm interested in coding.", admin_status: "download", created_at: "2016-08-16 22:38:05", updated_at: "2016-08-16 22:38:05", city_id: 2, profile_image_file_name: "Screen_Shot_2016-07-02_at_4.41.32_PM.png", profile_image_content_type: "image/png", profile_image_file_size: 324372, profile_image_updated_at: "2016-08-16 22:38:04"> 

first方法被調用時,它返回鍵 - 值對。我想要的只有值,ActiveRecord中是否有一個方法可以爲我們做到這一點?

回答

3

我延長@ Deepak的答案,以確保爲了保持相同的,因爲它是爲column_names,這是我是如何實現的:

User.first.attributes.values_at *User.column_names 
1

就可以轉換ActiveRecord的哈希然後得到的值,如下:

User.first.as_json.values 
+1

稍後會接受答案。 –

+0

你應該等待大約10分鐘:D ...謝謝你:) –

7

您還可以使用attributes方法得到它

User.first.attributes.values 
  1. User.first.attributes將返回哈希代表user物體

    User.first.attributes 
    
    { 
        "id" => 1, 
        "email" => "[email protected]", 
        "tel" => "+923223333333", 
        "interests" => "Hi, I'm interested in coding.", 
        "admin_status" => "download", 
        "created_at" => "2016-08-16 22:38:05", 
        "updated_at" => "2016-08-16 22:38:05", 
        "city_id" => 2, 
        "profile_image_file_name" => "Screen_Shot_2016-07-02_at_4.41.32_PM.png", 
        "profile_image_content_type" => "image/png", 
        "profile_image_file_size" => 324372, 
        "profile_image_updated_at" => "2016-08-16 22:38:04" 
    } 
    
  2. values將返回的值在Array

    User.first.attributes.values 
    
    [1, "[email protected]", "+923223333333", "Hi, I'm interested in coding.", "download", "2016-08-16 22:38:05", "2016-08-16 22:38:05", 2, "Screen_Shot_2016-07-02_at_4.41.32_PM.png", "image/png", 324372, "2016-08-16 22:38:04"] 
    
+0

我刪除了我的答案,贊成你的。但是我不確定'values'版本是否有用,因爲屬性的順序在'attributes'哈希中不能保證。在哈希中沒有固定的確定性順序,您無法確定數組中值的順序。這會讓以後很難真正讀取該數組中的屬性。 – spickermann

+0

@spickermann以某種方式它是確定性的。因爲ruby 1.9的值按照它們被添加到散列的順序返回。我認爲這是相對保存(但不能保證),假設在Rails中,每次屬性都以相同的順序添加到屬性Hash中。 – slowjack2k

+0

這可能取決於數據庫引擎,除非Rails在將值添加到屬性哈希值之前對列名進行排序。由於MySQL例如不能保證任何順序(除非你自己指定一個順序),我會懷疑結果是確定性的。 – spickermann

1
Object.first.attributes.values