简体   繁体   中英

Storing Location Data in the Database

I need to store data about specific Objects which include information about Location(Country, City, District) of an object. I'm trying to figure out the best way to store described above location data in the MySQL database and how it should look like in the rails active model.

My dummy idea is to create 3 separate tables like below:

Location_countries
    id
    name

Location_cities
    id
    country_id
    name
Location_districts
    id
    city_id
    name 

Create a separate table for an object and call it the item_location and include Ids of object its country... so on

Next is to create 3 Rails models (Country, City, Districts).. , but I think it's a very dirty way and it can be combined into the single Model like Item_location

Any Ideas?

Thank you in advance!

I don't entirely understand what you're looking to do, but either way, here's how I'd tackle it:

#app/models/object.rb
Class Object < ActiveRecord::Base
   has_one :location
end

#app/models/location.rb
Class Location < ActiveRecord::Base
   belongs_to :object
   belongs_to :city
   belongs_to :district

   delegate :name, to: :city, prefix: true
   delegate :name, to: :district, prefix: true
end

#app/models/city.rb
Class City < ActiveRecord::Base
   has_many :locations
   belongs_to :country
end

#app/models/district.rb
Class District < ActiveRecord::Base
  has_many :locations
end

#app/models/country.rb
Class Country < ActiveRecord::Base
  has_many :cities
end

This will give you the ability to call:

@object = Object.find params[:id]
@object.location.city_name
@object.location.district_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM