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 の方法」があるかどうかはわかりません (エレガントに)