Like a hidden array object hash in rails
I have a hash with an array object:
{
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>]
}
how to convert above hash to hash
{
false=>[{id:1, name:"campaign 1"}, {id:3, name: "capaign 3"}, ....],
true =>[{id:2, name:"campaign 2"}]
}
hash.each {|k,v| hash[k] = v.map{|e| {id: e[:id], name: e[:name]}}}
and if you can use the method select_all
, get a hash array, not an object array, so you don't need to hide the object for the hash.
ModelName.connection.select_all("select id, name from <table_name>;")
=> [{id:xxx, name: xxx}.......]
Use the attributes method for your object.
attributes () public
Returns a hash of all attributes with names in the form of keys and attribute values as values.
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>]
}
So this line should do the trick -
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}]
}