以下是我查询获取国家/地区列表的信息:
@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
输出结果如下:
Object[city:"Bangkok",country:"Thailand"],Object[city:"Phuket",country:"Thailand"],Object[city:"Malaysia",country:"Kuala Lumpur"],Object[city:"Malaysia",country:"Penang"],Object[city:"Shanghai",country:"China"],Object[city:"Beijing",country:"China"]
cchs = @countries_cities.group_by{|cc| cc["country"]}
@search_location_country = cchs
观点是:
<ul id="color-dropdown-menu" class="dropdown-menu dropdown-menu-right" role="menu">
<% @search_location_country.each do |country, cities| %>
<li class="input" style="background:#ECECEC; "><a href="#" style="font-weight: bold;"><%= country.upcase %></a></li>
<% cities.each do |city| %>
<li class="input"><a href="#"><%= city["city"].titleize %></a></li>
<% end %>
<% end %>
</ul>
现在下拉结果遵循以下模式:
Thailand
-Bangkok
-Phuket
Malaysia
-Kuala Lumpur
-Penang
China
-Beijing
-Shanghai
如何确保Malaysia
始终位于下拉列表的顶部?谢谢!
答案 0 :(得分:1)
怎么样:
@countries_cities = Product.joins(:user)
.where.not(country: [nil, ''])
.where(users: {merchant_status: 1})
.group(:country, :city)
.order("country!= 'Malaysia'")
.select(:country, :city)
.as_json
在Postgres中,false
在true
之前排序(请参阅此答案:Custom ORDER BY Explanation)
答案 1 :(得分:0)
您可以像这样自定义查询:
@countries_cities = Product.joins(:user)
.where.not(country: [nil, ''])
.where(:users => {:merchant_status => 1})
.group(:country, :city)
.order("ORDER BY
CASE WHEN country = 'Malaysia' THEN 1
ELSE 2
END ASC")
.select(:country, :city)
.as_json
所以我们设定马来西亚= 2的顺序,其他= 1,以确保马来西亚的结果将是最高的。