可以使用 column_names
来获取一个表的所有列,但是如果想知道ActiveRecord中某一特定实例的所有值呢。
比如说,如果想知道ActiveRecord中某一实例的所有值,那么
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中有没有一个方法可以帮我们做到这一点?
你也可以使用 attributes
取法
User.first.attributes.values
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"
}
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"]
我扩展了 @deepak 的答案,以确保顺序与现在的一样。column_names
这就是我如何实现的。
User.first.attributes.values_at *User.column_names
只需得到值,不管顺序。
User.first.attributes.values
你可以把activerecord转换为Hash 然后得到如下的值:
User.first.as_json.values
Object.first.attributes.values