Rails与城市一起获得独特的国家

如何列出相关城市后面的唯一国家/地区? 以下是我的产品表:

name country city p1 US New York p2 US Boston p3 US Chicago k1 UK London k2 UK Liverpool 

控制器:

 @countries = Product.joins(:user).distinct.where("country is not null and country  ''").where(:users => {:merchant_status => 1}).pluck(:country) @cities = Product.joins(:user).distinct.where("city is not null and city  ''").where(:users => {:merchant_status => 1}).pluck(:city) @countries.map! {|country| country.split.map(&:capitalize).join(' ')} @search_location_country = @countries 

在我看来:

  

如何对下拉列表的最终结果进行排序,如下所示:

 US - New York - Boston - Chicago UK - London - Liverpool 

谢谢!!

编辑

要显示如下内容:

在此处输入图像描述

嘿,你可以尝试这种方式使用group它给你所有不同的记录

 @countries_cities = Product.joins(:user).where("country is not null and country <> ''").where("city is not null and city <> ''").where(:users => {:merchant_status => 1}).group(:country, :city).select("country,city").as_json 

它会给你输出像

 [{:country => "US", :city => "New York"}..] 

如果你想再按国家分组,那就用了

 cchs = @countries_cities.group_by{|cc| cc["country"]} 

将上面的多维数组转换为哈希值

 @country_cities_hash = = Hash[*cchs] 

在您的视图文件中

 <% @country_cities_hash.each do |country, cities| %> 
  • <%= country %>
  • <% cities.each do |city| %>
  • <%= "#{city}(#{country})" %>
  • <% end %> <% end %>

    不确定我是否明白这个问题,但是…我想你有一个Product的集合,看起来像这样:

     produts = [ , , , ... ] 

    在这种情况下,按国家/地区索引城市名称:

     @cities_by_coutry = products.inject({}) do |index, product| index[product.country] ||= [] index[product.country] << product.city index end 

    结果如下:

     {"US"=>["New York", "Boston"], "FR"=>["Paris"]} 

    然后你可以迭代:

     @cities_by_coutry.each do |country, cities| cities.each do |city| puts "City: #{city} is in country {country}" end end