["name", "age", "phon-6ren">
gpt4 book ai didi

ruby-on-rails - 将 Active Record 对象转换为哈希

转载 作者:行者123 更新时间:2023-12-02 03:14:13 24 4
gpt4 key购买 nike

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

{
"email1" => ["name", "age", "phone_number"],
"email2" => ["name2", "age2", "phone_number2"]
....
}

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

最佳答案

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

Hash[Person.all.collect { |user| [user.email, user.attributes.except(:email).values] }]

如果您想省略其他属性,例如 created_atupdated_at,请运行

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

关于ruby-on-rails - 将 Active Record 对象转换为哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56632311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com