轨道4中的多级连接

May*_*tel 2 join ruby-on-rails

我想在rails 4中进行此查询

select r.region_id, r.region_name from countries c, zones z, regions r where c.country_id = $country_id (pass as parameter) and c.country_id = z.zone_id and z.subzone_id = r.region_id
Run Code Online (Sandbox Code Playgroud)

楷模 :

 #Country.rb
class Country < ActiveRecord::Base
  has_one :place, foreign_key: :place_id
  has_many :zones , foreign_key: :place_id
  has_many :subzones, :through => :zones
end

#Zone.rb
class Zone < ActiveRecord::Base
 belongs_to :place
 belongs_to :subzone, :class_name => 'Place' , :foreign_key => :subzone_id
end

#Region.rb
class Region < ActiveRecord::Base
  has_one :place , foreign_key: :place_id
end

#Place.rb
class Place < ActiveRecord::Base
  belongs_to :region, :foreign_key => :place_id
  has_many :zones, :foreign_key => :place_id
  has_many :subzones, :through => :zones
end
Run Code Online (Sandbox Code Playgroud)

我试过这个:

Country.joins(:zones).where("zone.subzone_id = regions.region_id AND country_id = ?",$country_id )
Run Code Online (Sandbox Code Playgroud)

但得到的错误是:

Java::JavaSql::SQLSyntaxErrorException: ORA-00904: "REGIONS"."REGION_ID": invalid identifier.....
Run Code Online (Sandbox Code Playgroud)

不确定如何在上面的查询中加载区域...

提前致谢 :-)

kha*_*maa 7

Region.joins(zones: :country).where(country: {country_id: $country_id})
Run Code Online (Sandbox Code Playgroud)

只有拥有这样的模型时,这才有效:

#Country.rb
class Country < ActiveRecord::Base
  has_many :zones, as: :zone
end
#Zone.rb
class Zone < ActiveRecord::Base
  has_many :regions, as: :region
  belongs_to :country, foreign_key: :zone_id
end

#Region.rb
class Region < ActiveRecord::Base
  belongs_to :zone, foreign_key: :region_id
end
Run Code Online (Sandbox Code Playgroud)