I am using Ruby on Rails v3.2.2. I have following model classes
class Country < ActiveRecord::Base
has_many :regions, :foreign_key => 'country_id'
end
class Region < ActiveRecord::Base
belongs_to :country, :foreign_key => 'country_id'
has_many :cities, :foreign_key => 'region_id'
end
class City < ActiveRecord::Base
belongs_to :region, :foreign_key => 'region_id'
end
and I would like to make a City belongs_to :country.
I know that the simplest way to make that is to add a country_id database table column to the City database table and to state related ActiveRecord Associations, this way:
class Country < ActiveRecord::Base
# ...
has_many :cities, :foreign_key => 'country_id'
end
class City < ActiveRecord::Base
# ...
belongs_to :country, :foreign_key => 'country_id'
end
However, in order to store less database data, I think I may "use" the data already stored in the Region table since a city belongs to a region which in turn belongs to a country (this implies that a city belongs to a country) but, in this case, I have no idea on how to properly state ActiveRecord Associations for City and Country so to "exploit" mentioned relationship informations implicitly present "through" the Region model class.
How should I proceed?
Note: I am "forcing" to state the belongs_to :country ActiveRecord Association in the City model class because I would like to use the RoR :counter_cache feature (available only for belongs_to associations) in order to count cities present in a country.