0

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?

1
  • I found this answer to do that you want Commented Jul 13, 2021 at 9:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.