如何将数组对象转换为rails中的哈希值

时间:2015-10-27 08:27:16

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我有一个数组对象的哈希:

{
  false=>[#<Campaign id: 1, name: "campaign 1", active: false>, #<Campaign id: 3, name: "campaign 3", active: false>, #<Campaign id: 4, name: "campaign 4", active: false>], 
  true=>[#<Campaign id: 2, name: "campaign 2", active: true>]
} 

如何将上面的哈希转换为哈希

{
  false=>[{id:1, name:"campaign 1"}, {id:3, name: "capaign 3"}, ....],
  true =>[{id:2, name:"campaign 2"}]
}

2 个答案:

答案 0 :(得分:3)

hash.each {|k,v| hash[k] = v.map{|e| {id: e[:id], name: e[:name]}}}

如果你可以使用select_all方法获取哈希数组,而不是对象数组,那么你就不需要将对象隐藏为哈希。

ModelName.connection.select_all("select id, name from <table_name>;")
=> [{id:xxx, name: xxx}.......]

答案 1 :(得分:0)

在对象上使用attributes方法

  

attributes() public

     

返回所有属性的哈希值,其名称为键,属性值为值。

hash = {
  false => [#<Campaign id: 1, name: "campaign 1", active: false>, #<Campaign id: 3, name: "campaign 3", active: false>, #<Campaign id: 4, name: "campaign 4", active: false>], 
  true  => [#<Campaign id: 2, name: "campaign 2", active: true>]
} 

所以这一行应该可以解决问题 -

hash.each {|k, v| hash[k] = v.map(&:attributes) }

{
  false => [{"id": 1, "name": "campaign 1", "active": false}, {"id": 3, "name": "campaign 3", "active": false}, {"id": 4, "name": "campaign 4", "active": false}], 
  true  => [{"id": 2, "name": "campaign 2", "active": true}]
}