在Rails中对部分排序的列表进行排序 [英] Sorting a Partially sorted list in Rails
问题描述
这个问题最初源于我在此处发表的另一篇SO帖子.但是,该问题实际上是一个Rails问题,我试图简化该问题以使其更简单,这将使我的答案更易于管理,并且不会使有兴趣的人感到沮丧.这是原始问题:
This question originally stems from another SO post I made here. However, the problem was in fact a Rails problem, and I tried to strip down the problem to make it more simple, which would give me answers more manageable and not frustrate individuals interested in helping. Here's the original problem:
在我的initializers文件夹中,我有一个非常复杂的集合,即带有数组的哈希散列.该集合如下所示:
In my initializers folder, I had a really complex collection, a hash of hashes with arrays. The collection looks like the following:
Locations = { :Australia => { :cities => %w(Sidney Melbourne Other),
:currency => 'AUD'},
:Canada => { :cities => %w(Montreal Toronto Other),
:currency => 'CAD'},
:England => { :cities => %w(London Other),
:currency => 'GBP'},
:Israel => { :cities => ['Jerusalem', 'Tel Aviv', "Modi'in", 'Netanya', 'Haifa', 'Other'],
:currency => 'ILS'},
:USA => { :cities => ['Chicago', 'Los Angeles', 'Miami', 'Teaneck', 'New York', 'Brooklyn', 'Queens', 'Bronx',
'Washington', 'Other'],
:currency => 'USD'},
:France => { :cities => %w(Paris Other),
:currency => 'EUR'},
:Switzerland => { :cities => %w(Zurich Antwerp Other),
:currency => 'CHF'},
:South_Africa => { :cities => ['Johannesburg', 'Cape Town', 'Other'],
:currency => 'ZAR'},
:Argentina => { :cities => ['Buenos Aires', 'Other'],
:currency => 'ARS'}
}
在我看来,我使用初始化程序对选定国家/地区的城市进行了以下排序:
In my views, I used the initializer to the sort the cities of the selected country with the following:
tr
-city_select = Locations.collect { |country_name, country_info | country_info[:cities].collect {|city| [city, city, class: country_name] } }.flatten(1)
th
= f.label :city, '*City'
td
= f.select :city, city_select, {}, id: 'property_city'
问题在于,当我选择下拉列表中的城市(选择国家/地区)后,该列表将无法排序.如果我刚在块{| city |上添加了.sort
, [city,city,class:country_name]}.sort,城市组将按字母顺序排序,包括单词"Other".我不知道如何对城市列表进行部分排序,并在末尾附加成员其他".
The problem was that when I selected the drop down, city, after selecting the country, the list would be unsorted. If I just added, .sort
, on the block {|city| [city, city, class: country_name]}.sort, the group of cities would be sorted alphabetically, including the word "Other". I did not know how to partially sort the list of cities and append the member, Other, at the end.
推荐答案
感谢@wayneThis回答我的问题:
Thanks to @wayneThis answer my question:
tr
-city_select = Locations.collect { |country_name, country_info | country_info[:cities].collect {|city| [city, city, class: country_name] }.sort_by { |(city)| [city == "Other" ? 1 : 0, city]}.push(["Other"]) }.flatten(1)
th
= f.label :city, '*City'
td
= f.select :city, city_select, {}, id: 'property_city'
由于@WayneConrad和@bjhaid,我得以解决我的问题.
Thanks to @WayneConrad and @bjhaid, I was able to solve my problem.
这篇关于在Rails中对部分排序的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!