执行join
后,我得到了这两个哈希数组数组1
[#<State id: 1, name: "Alabama">, #<State id: 1, name: "Alabama">, #<State id: 1, name: "Alabama">, #<State id: 1, name: "Alabama">, #<State id: 2, name: "Alaska">, #<State id: 2, name: "Alaska">, #<State id: 4, name: "Arkansas">, #<State id: 4, name: "Arkansas">, #<State id: 4, name: "Arkansas">, #<State id: 6, name: "Colorado">, #<State id: 6, name: "Colorado">, #<State id: 6, name: "Colorado">, #<State id: 11, name: "Georgia">, #<State id: 14, name: "Illinois">, #<State id: 18, name: "Kentucky">, #<State id: 18, name: "Kentucky">, #<State id: 22, name: "Massachusetts">, #<State id: 48, name: "Washington">]
阵列2
[#<City id: 1, name: "Abbeville", state_id: 1>, #<City id: 1, name: "Abbeville", state_id: 1>, #<City id: 1, name: "Abbeville", state_id: 1>, #<City id: 4543, name: "Abingdon", state_id: 14>, #<City id: 8282, name: "Accord", state_id: 22>, #<City id: 3808, name: "Acworth", state_id: 11>, #<City id: 6855, name: "Adairville", state_id: 18>, #<City id: 6855, name: "Adairville", state_id: 18>, #<City id: 18895, name: "Adams County", state_id: 6>, #<City id: 4, name: "Addison", state_id: 1>, #<City id: 4, name: "Addison", state_id: 1>, #<City id: 17510, name: "Addy", state_id: 48>, #<City id: 1054, name: "Adona", state_id: 4>, #<City id: 1054, name: "Adona", state_id: 4>, #<City id: 577, name: "Akiachak", state_id: 2>, #<City id: 1056, name: "Alicia", state_id: 4>, #<City id: 583, name: "Ambler", state_id: 2>, #<City id: 2783, name: "Aspen", state_id: 6>]
我想根据每个数组中的state_id的值
从上面的两个数组中创建第三个数组 例如,在这种情况下[#,....等等
为你的帮助我使用连接查询的前两个哈希数组
@states = State.joins("INNER JOIN property_of_interests ON property_of_interests.state_id = states.id").where(:property_of_interests => {:user_id => current_user.id})
@cities = City.joins("INNER JOIN property_of_interests ON property_of_interests.city_id = cities.id").where(:property_of_interests => {:user_id => current_user.id})
我可以处理查询本身以获得所需的输出吗?
我试过像
这样的东西`@states.select("@states.name,@cities.name").joins("INNER JOIN @cities ON @cities.state_id = @states.id")`
但它不起作用。
更多信息
状态 id,name
城市 id,name,state_id
property_of_interests id,user_id,state_id,state_name
所需的输出,如
State Name City Name
Alabama Abbeville
Alabama Abbeville
Alabama Abbeville
....
答案 0 :(得分:1)
您可以这样做:
City.all.each do |city|
puts "#{city.state.name} #{city.name}"
end
或者,作为一个数组:
arr = City.all.map { |c| [c.state.name, c.name] }
或者作为哈希数组:
arr = City.all.map { |c| {state: c.state.name, city: c.name} }
或者实际回答这个问题,因为你想从properties_of_interest表开始:
PropertyOfInterest.all.each do |prop|
prop.state.cities.each do |city|
puts prop.state.name, city.name
end
end