我有一个名为 Place 的父类。
# Parent class for Country, City and District
class Place < ActiveRecord::Base
end
class Country < Place
has_many :cities, foreign_key: "parent_id"
has_many :districts, through: :cities
end
class City < Place
belongs_to :country, foreign_key: "parent_id"
has_many :districts, foreign_key: "parent_id"
end
class District < Place
belongs_to :city, foreign_key: 'parent_id'
has_one :country, through: :city
end
架构:
create_table "places", force: true do |t|
t.string "name"
t.string "type"
t.integer "parent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "places", ["parent_id"], name: "index_places_on_parent_id"
add_index "places", ["type"], name: "index_places_on_type"
以下按预期工作:
@country.cities # => Returns all of the cities that belong to this country
@city.districts # => Returns all of the districts that belong to this city
但这并不像我想象的那样工作:
@country.districts # => Does not return all of the districts belonging to cities in this country
谁能解释我应该如何处理性传播感染?
更新
这是来自的输出 SQL 查询@country.districts
SELECT "places".* FROM "places" INNER JOIN "places" "cities_districts_join" ON "places"."parent_id" = "cities_districts_join"."id" WHERE "places"."type" IN ('City') AND "places"."type" IN ('District') AND "cities_districts_join"."parent_id" = ? [["parent_id", 1]]
我认为问题在于它对两个关系使用相同的连接表,但我不确定是否有“Rails 方式”来更改连接表的名称(优雅地)