2016-03-29 35 views
0

如何列出獨特的國家,其次是相關城市?下面是我的產品表: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 

在我看來:

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

我如何排序的最終結果下拉這樣的:

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

謝謝!

編輯

要顯示這樣的事情:

enter image description here

+0

是什麼'@城市'爲? – sschmeck

+0

@sschmeck城市我用於搜索沒有下拉。所有的國家和城市搜索工作都很好,但我需要理清它的顯示方式。國家其次是城市名單 – d3bug3r

+0

你正在尋找select2元素或類似的我tink – Guru

回答

1

嘿,你可以嘗試使用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| %> 
    <li class="input"><a href="#"><%= country %></a></li> 
<% cities.each do |city| %> 
    <li class="input"><a href="#"><%= "#{city}(#{country})" %></a></li> 
    <% end %> 
<% end %> 
+0

我怎樣才能修改了顯示國家>城市的視圖? – d3bug3r

+0

編輯過的查看文件 –

+0

結果顯示不正確.. – d3bug3r

1

不湊我確定我明白這個問題,但是......我想你有一個產品集合,看起來像這樣:

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

在這種情況下,指數的城市名稱按國家:

@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