2016-07-25 35 views
0

我试图通过降序排列显示median_salary订购的作业列表。到目前为止,它似乎只考虑了第一批median_salary。因此,像900 1000上面列出,即使1000的值> 900Rails:如何通过控制器中的降序进行订购

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,它似乎暗示了我目前正在写这种东西的方式。

任何见解或建议将有所帮助。谢谢!

+1

您median_salary字段是一个字符串,这就是为什么你有这个问题。您需要通过迁移或'to_i'方法将您的字符串类型更改为int。 –

回答

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的订单条款应是这样的:

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

这对我有用。我希望能够用逗号(即12,000)显示'median_salary',但它并没有结束工作。我创建了迁移来将'median_salary'类型改为float。但是,上面的代码投入浮动的工作也是如此。 – teresa

+0

您是否尝试过[number_to_currency](http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency)helper? – teksisto

1

正如@teksisto说,你应该改变median_salary浮法或者一些接受小数的类型。另外,我建议建立在模型中的一个范围,在你的Highestpaidjob模型类似

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

。然后,您只需在您喜欢的应用程序的任何地方拨打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 

希望它能帮助。谢谢!

+0

我将'median_salary'的迁移从字符串更改为浮动,并尝试了您的建议。这是一个很好的解决方案,我真的不知道如何使用示波器。但是这使我的应用程序更容易阅读。谢谢! – teresa

+0

@tshckr不客气=) –

相关问题