将 Active Record 对象转换为哈希

a_k*_*k_v 2 ruby ruby-on-rails ruby-on-rails-5

我有一个模型人物,其中包含电子邮件、姓名、年龄、电话号码字段。我想转换Person.all为哈希值。哈希值应具有如下结构:

{
"email1" => ["name", "age", "phone_number"],
"email2" => ["name2", "age2", "phone_number2"]
....
}
Run Code Online (Sandbox Code Playgroud)

我尝试过as_jsonmapattributes等等。但它返回哈希数组。我如何创建这个自定义结构?

ray*_*ray 5

您可以从下面的查询中获取它,

Hash[Person.all.collect { |user| [user.email, user.attributes.except(:email).values] }]
Run Code Online (Sandbox Code Playgroud)

如果您想省略其他属性,例如created_at& updated_at,请运行

Hash[Person.all.collect { |user| [user.email, user.attributes.except(:email, :created_at, :updated_at).values] }]
Run Code Online (Sandbox Code Playgroud)

  • 在最近的红宝石中,您可以使用 `Hash#to_h` 而不是 `Hash#[]`,后者更具语义性,`[[:a, 3]].to_h # -> {:a=>3} ` (2认同)