Rails拥有城市的独特国家 [英] Rails get unique country with cities
本文介绍了Rails拥有城市的独特国家的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何列出唯一的国家和相关城市?以下是我的产品表:
How can I list unique country followed by related cities? Following were my product table:
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
在我看来:
<ul id="color-dropdown-menu" class="dropdown-menu dropdown-menu-right" role="menu">
<% @search_location_country.each do |country| %>
<li class="input"><a href="#"><%= country %></a></li>
<% end %>
</ul>
如何对最终结果进行排序,如下所示:
How can I sort the end result for drop down like this:
US
- New York
- Boston
- Chicago
UK
- London
- Liverpool
谢谢!
编辑
要显示如下内容:
推荐答案
嘿,您可以使用 group
尝试这种方式不同的记录
Hey you can try this way using group
it gives you all distinct records
@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
它将为您提供输出,例如
It will give you output like
[{:country => "US", :city => "New York"}..]
如果要再次按国家/地区分组,请使用
If you want to again group it by country then used like
cchs = @countries_cities.group_by{|cc| cc["country"]}
将上述多维数组转换为使用
Convert above multidimensional array to hash using
@country_cities_hash = = Hash[*cchs]
在您的视图文件中为
<% @country_cities_hash.each do |country, cities| %>
<li class="input"><a href="#"><%= country %></a></li>
<% cities.each do |city| %>
<li class="input"><a href="#"><%= "#{city}(#{country})" %></a></li>
<% end %>
<% end %>
这篇关于Rails拥有城市的独特国家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文