是否可以根据特定顺序对Rails中的国家/地区进行排序?

时间:2019-11-27 16:59:31

标签: ruby-on-rails arrays ruby

我正在尝试按国家/地区订购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

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

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

谢谢

1 个答案:

答案 0 :(得分:0)

我们以Stefan's comment为基础,首先可以按发布年份排序,然后按特殊的国家/地区顺序排序,然后再按国家/地区排序。

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