gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:41:45 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com