问题
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