ruby-on-rails - rails 4 中的多级连接

标签 ruby-on-rails join

我想在 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.....

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

提前致谢:-)

最佳答案

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

关于ruby-on-rails - rails 4 中的多级连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29678269/

相关文章:

ruby-on-rails - fields_for 表单生成器对象为零

ruby-on-rails - Rails Controller 中有多个before_action?

sql - 连接三个表创建的 View ,一个表与另一个表相似

mysql - 返回表中某一列中的值多次出现的行

java - 使用和重用 Phaser 而不是 join()

ruby-on-rails - 如何在 shoulda 宏中创建上下文

ruby-on-rails - 如果数据库中为空值则显示字符串

Javascript桌面浏览器从相机获取头像

SQL连接两个表以从第二个表中拆分电子邮件

mysql - 如何在mysql中合并多个select