在ruby中从ActiveRecord对象创建嵌套哈希

时间:2015-04-16 06:22:31

标签: ruby arrays json activerecord hash

require "active_record"

ActiveRecord::Base.establish_connection(
  :adapter  => 'mysql2',
  :database => '<db_name>',
  :username => '<username>',
  :password => '<password>',
  :host     => 'localhost')

ActiveRecord::Base.pluralize_table_names = false

class Location < ActiveRecord::Base
    has_many :location_channels
    has_many :channels, :through => :location_channels
end

class Channel < ActiveRecord::Base  
    has_many :location_channels
    has_many :locations, :through => :location_channels
end

class LocationChannel < ActiveRecord::Base  
    belongs_to :location
    belongs_to :channel
end

locations = Location.all

hash = {} # hash initialization

locations.each do |location|
    hash["location"] = location[:name]
        puts "#{location[:name]} has #{location.channels.size} channels:"
            location.channels.each do |channel|
                puts "--> #{channel[:name]}"
            end
        puts
end

puts hash

最终目标是创建一个 JSON 文件

所以我决定从JSON创建Hash object更容易。

与上面的代码一样,我可以通过名为LocationChannel类的JOIN表访问嵌套文档,并且我试图弄清楚如何创建Hash object看起来像:

{ 
  ["location" => "A", "channels" => {"1","2","3"}], 
  ["location" => "B", "channels" => {"1","2"}], 
  ["location" => "C", "channels" => {"4","5","6"}]
}

其中"A""B""C" - 位置名称和"1""2"等 - 代表频道名称。

当前代码仅打印出最后一条记录,如:

{"location"=>"A"}

如果上面的示例错误,请纠正Hash的样子。

更新1

感谢@jonsnow指出哈希格式。

哈希格式应为:

{ :locations =>
    [
       { name: a, channels: [1,2,3]}, 
       { name: b, channels: [1,2]},
       { name: c, channels: [4,5,6]}
    ]
}

1 个答案:

答案 0 :(得分:1)

更新哈希的解决方案,

hash = { locations: [] } # hash initialization

locations.each do |location|
  hash[:locations] << { name: location.name,
  channels:  location.channels.pluck(:name) }
end