我需要存储有关特定对象的数据,其中包含有关对象的位置(国家,城市,区)的信息。我试图找出在MySQL数据库中存储上述位置数据的最佳方法,以及它在rails活动模型中的外观。
我的想法是创建3个单独的表,如下所示:
Location_countries
id
name
Location_cities
id
country_id
name
Location_districts
id
city_id
name
为对象创建一个单独的表,并将其命名为item_location,并将对象的ID包含在其国家/地区......等等
接下来是创建3个Rails模型(Country,City,Districts)..但是我认为这是一种非常肮脏的方式,它可以组合成单个模型,如Item_location
任何想法?
提前谢谢!
答案 0 :(得分:1)
我完全不了解你的目标,但无论哪种方式,我都是如何解决的:
#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
这将使您能够致电:
@object = Object.find params[:id]
@object.location.city_name
@object.location.district_name