Created
January 28, 2015 08:14
-
-
Save avakhov/2892231dddb0995fade4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "rubygems" | |
require "active_record" | |
ActiveRecord::Base.establish_connection "postgres://localhost/geo" | |
ActiveRecord::Base.connection.create_table("planets") do |t| | |
t.string :name | |
end | |
ActiveRecord::Base.connection.create_table("countries") do |t| | |
t.belongs_to :planet | |
t.string :name | |
end | |
ActiveRecord::Base.connection.create_table("cities") do |t| | |
t.belongs_to :country | |
t.string :name | |
end | |
class Planet < ActiveRecord::Base | |
has_many :countries | |
end | |
class Country < ActiveRecord::Base | |
has_many :cities | |
end | |
class City < ActiveRecord::Base | |
end | |
Planet.create!(name: "Earth").tap { |planet| | |
planet.countries.create!(name: "Russia").tap { |ru| | |
ru.cities.create!(name: "Moscow") | |
ru.cities.create!(name: "Perm") | |
} | |
} | |
Planet.create!(name: "Mars").tap { |planet| | |
planet.countries.create!(name: "Red Country").tap { |ru| | |
ru.cities.create!(name: "Red City") | |
} | |
} | |
p Planet. | |
includes(:countries => :cities). | |
flat_map(&:countries).flat_map(&:cities). | |
map(&:name) | |
# => ["Moscow", "Perm", "Red City"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment