按字段排序,存储为字符串,但排序为整数rails

时间:2016-03-19 21:10:41

标签: ruby-on-rails

我犯了一个错误并使用字符串字段而不是整数生成了我的Item模型。 这是我的迁移

class CreateItems < ActiveRecord::Migration
  def change
    create_table :items do |t|
      t.string :name
      t.string :url

      t.text :photo

      t.string :price


      t.timestamps null: false
    end
  end
end

但是现在我想按价格字段对我的项目进行排序,并且rails会以错误的方式对其进行排序,因为它存储为字符串。 例如,它认为价格9大于1111111111。 现在我点这样订购:

@items=Item.where(:category_id => @active_category_id).order(:price)

我该怎么办?

2 个答案:

答案 0 :(得分:2)

修复列类型。您可以通过以下迁移来完成此操作:

class ChangePriceTypeInItems < ActiveRecord::Migration
  def change
    change_column :items, :price, :integer
  end
end

如果包含的字符串表示整数值,则price列中的数据将被保留。

enter image description here

  

顺便说一句,我认为price必须是decimal而不是integer。但是,你选择。

答案 1 :(得分:1)

试试这个:

@items = Item.where(category_id: @active_category_id).sort { |a, b| b.price.to_i <=> a.price.to_i }

这将获得您的类别ID,然后将价格作为整数而不是字符串进行比较。它应该给你你正在寻找的订单。

相关问题