我想在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
模特:
#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
我试过这个:
Country.joins(:zones).where("zone.subzone_id = regions.region_id AND country_id = ?",$country_id )
但得到错误:
Java::JavaSql::SQLSyntaxErrorException: ORA-00904: "REGIONS"."REGION_ID": invalid identifier.....
不确定如何在上面的查询中加载区域...
提前致谢: - )
答案 0 :(得分:7)
Region.joins(zones: :country).where(country: {country_id: $country_id})
这只有在您拥有这样的模型时才有效:
#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
答案 1 :(得分:0)
在join或include之后的where语句中使用string时,需要使用表名,而不是引用的关系名,所以你写的地方
zone.subzone_id
你需要写
zones.subzone_id
你的模型和关系有点令人困惑,很难看出你试图与他们建立关系,place_id似乎被用作许多与Place类无关的东西的参考,它将来可能会有点混乱。 然而,就我所能掌握的而言,就多级联接而言,如:
Country.joins(zones: {place: :region}).where.........
与您要为查询设置表连接的内容类似。玩那些或类似的东西,希望它有所帮助。