【问题标题】:How to order by descending value in controller?如何在控制器中按降序排序?
【发布时间】:2016-07-25 18:53:29
【问题描述】:

我正在尝试按降序显示由median_salary 排序的作业列表。到目前为止,它似乎只考虑了median_salary的第一个数字。所以像 900 这样的东西列在 1000 之上,即使 1000 > 900 的值。

homes_controller.rb:

def index
  nyc_highest = Highestpaidjob.where("city = ?", "NYC")
  @nyc_highest = nyc_highest.order("median_salary DESC")
end

index.html.erb:

<%= @nyc_highest.inspect %>

返回:

#<ActiveRecord::Relation [#<Highestpaidjob id: 11, job: "Architect, City Planner", median_salary: "95928.48", count: 237, margin_of_error: "", city: "NYC", state: "New York", created_at: "2016-07-25 18:17:17", updated_at: "2016-07-25 18:17:17">, #<Highestpaidjob id: 7, job: "Medical", median_salary: "170507.69", count: 128, margin_of_error: "", city: "NYC", state: "New York", created_at: "2016-07-25 18:09:30", updated_at: "2016-07-25 18:09:30">]>

它将 95928.48 列为高于 170507.69。我错过了一个条件吗?

我查看了Best way to implement sort asc or desc in rails,它似乎暗示了我目前编写排序的方式。

【问题讨论】:

  • 您的 median_salary 字段是一个字符串,这就是您遇到此问题的原因。您需要通过迁移或 to_i 方法将字符串类型更改为 int。

标签: ruby-on-rails sorting


【解决方案1】:

这是因为您的median_salary 数据库字段是字符串并且它被排序为字符串。您需要在 order 子句中将其转换为整数,或创建迁移,这将更改字段数据类型。

正在排序的字符串和正在排序的浮点数之间的区别:

irb(main):001:0> ["95928.48", "170507.69"].sort
=> ["170507.69", "95928.48"]
irb(main):002:0> [95928.48, 170507.69].sort
=> [95928.48, 170507.69]

在 postgres 中,您的 order 子句应如下所示:

@nyc_highest = nyc_highest.order("CAST(median_salary as FLOAT) DESC")

【讨论】:

  • 这对我有用。我希望能够显示带有逗号的median_salary(即12,000),但它最终没有工作。我创建了迁移以将 median_salary 类型更改为浮动。但是上面转换为 float 的代码也可以正常工作。
  • 你试过number_to_currencyhelper吗?
【解决方案2】:

正如@teksisto 所说,您应该将median_salary 更改为浮点数或某种接受小数的类型。另外,我建议在您的模型上创建一个范围,例如

scope :nyc_highest, -> { where("city = ?", "NYC").order("median_salary DESC") }

在您的 Highestpaidjob 模型上。然后,您只需在您喜欢的应用程序的任何位置调用Highestpaidjob.nyc_highest

用于更改median_salary 数据类型:

rails g migration ChangeMedianSalaryType

然后编辑您的迁移文件:

class ChangeMedianSalaryType < ActiveRecord::Migration
  def up
    change_column :highestpaidjobs, :median_salary, :float
  end

  def down
    change_column :highestpaidjobs, :median_slary, :string
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    相关资源
    最近更新 更多