Rails get unique country with cities

限于喜欢 提交于 2019-12-12 03:36:58

问题


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

Controller:

@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

And in my View:

<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

Thanks!!

EDIT

To be display something like this:


回答1:


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]

In your view file as

<% @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 %>



回答2:


Not sure I do understand the question but... I guess you have a collection of Product, looking like this :

produts = [
  <Product @name="p1", @country="US" @city="New York">,
  <Product @name="p1", @country="US" @city="Boston">,
  <Product @name="k2", @country="FR" @city="Paris">,
  ...
]

In that case, to index the city names by country :

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

Which result to :

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

Then you can iterate :

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


来源:https://stackoverflow.com/questions/36277044/rails-get-unique-country-with-cities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!