首页 > 解决方案 > 有没有办法根据特定顺序对 Rails 中的国家/地区进行排序?

问题描述

我正在尝试按国家/地区在 Rails 中订购一个数组,但我希望某些国家/地区的功能比其他国家/地区更高,例如英国为 1,美国为 2,德国为 3,等等。

额外的复杂性是我首先需要按年订购。例如,如果一个记录是 1969 年在英国创建的,我希望它首先出现在 1969 年在德国的记录。

我尝试了以下方法,但我认为我什至不接近:

我的观点:

<% @versions.sort_by do |version | version.country_order %>
   <%= render 'version_card', version: version %>
 <% end %>

在版本模型中,我添加了这个方法:

def country_order
    return 0 if master.country_code == country_code
    return 1 if country_code == "UK"
    return 2 if country_code == "US"
    return 3 if country_code == "DE"
    return 4 if country_code == "FR"
    return 5 if country_code == "JP"
 end

最后在主控制器中(因为主控制器显示所有可用的版本):

def show
 @versions = Kaminari.paginate_array(versions_search).page(params[:page]).per(VERSIONS_PER_ROW)
 @versions.sort_by! { |version | version.release_year }
end

谢谢

标签: ruby-on-railsarraysruby

解决方案


基于Stefan 的评论,我们可以首先按发行年份排序,然后是特殊国家顺序,然后是国家本身。

class Version
  SPECIAL_COUNTRY_ORDER = ["UK", "US", "DE", "FR", "JP"]

  attr_accessor :country_code, :release_year

  def initialize(country_code:, release_year:)
    @country_code = country_code
    @release_year = release_year
  end

  def special_country_order
    SPECIAL_COUNTRY_ORDER.index(country_code) || SPECIAL_COUNTRY_ORDER.size
  end

  def to_s
    "#{country_code} #{release_year}"
  end
end

versions = [
  Version.new(country_code: "DE", release_year: 1969),
  Version.new(country_code: "UK", release_year: 1969),
  Version.new(country_code: "JP", release_year: 1999),
  Version.new(country_code: "AA", release_year: 1999),
  Version.new(country_code: "BB", release_year: 1999),
  Version.new(country_code: "ZZ", release_year: 1999),
  Version.new(country_code: "BB", release_year: 2000)
]

puts versions.sort_by { |version|
  [version.release_year, version.special_country_order, version.country_code]
}

如果一个国家没有特殊的国家顺序,它会得到一个比任何特殊国家都大的数字。因为它更大,所以排序低于它们。由于它是相同的数字,因此排序会转到下一个排序键:国家代码本身。

这是它的排序依据。

[1969, 2, "DE"]
[1969, 0, "UK"]
[1999, 4, "JP"]
[1999, 5, "AA"]
[1999, 5, "BB"]
[1999, 5, "ZZ"]
[2000, 5, "BB"]

和结果。

UK 1969
DE 1969
JP 1999
AA 1999
BB 1999
ZZ 1999
BB 2000

推荐阅读