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
Final goal is to create one JSON file.
So I decided it'll be easier to create JSON from Hash object.
As in the code above, I'm able to access nested documents via JOIN table called LocationChannel class and I'm trying to figure out how to create a Hash object what will look like:
{
["location" => "A", "channels" => {"1","2","3"}],
["location" => "B", "channels" => {"1","2"}],
["location" => "C", "channels" => {"4","5","6"}]
}
where "A", "B" and "C" - locations name and "1", "2", etc. - represents channels name.
And the current code prints out only the last record like:
{"location"=>"A"}
Please correct me how should Hash look like if the sample above is wrong.
UPDATE 1
Thanks to @jonsnow for point out the hash format.
Hash format should be:
{ :locations =>
[
{ name: a, channels: [1,2,3]},
{ name: b, channels: [1,2]},
{ name: c, channels: [4,5,6]}
]
}
["location" => "A", "channels" => {"1","2","3"}].key => valuepairs in your hash"location" => "A", 2nd pair: does it have to look"channels" => ["1","2","3"]?