user2950593
user2950593

Reputation: 9647

sort by field which is stored as string but sort as integer rails

I made an error and generated my Item model with string field instead of integer. Here is my migration

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

But right now I want to sort my items by price field and rails sorts it bad way because it is stored as string. For example it thinks that price 9 is bigger than 1111111111. Right now I order them like this:

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

What do I do?

Upvotes: 0

Views: 337

Answers (2)

Leantraxxx
Leantraxxx

Reputation: 4606

Fix the column type. You can do it with the following migration:

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

The data in price column will be preserved if the string contained represents an integer value.

enter image description here

By the way, I think a price needs to be a decimal not an integer. But, you choose.

Upvotes: 2

toddmetheny
toddmetheny

Reputation: 4453

try this:

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

this gets all with your category id and then compares the prices as integers instead of strings. It should give you the order you're looking for.

Upvotes: 1

Related Questions