简体   繁体   中英

How to sort table columns in ascending or descending order by clicking the header

I have a store with items . Each item has a price.

I tried to sort them by ascending prices and descending by pricing the price header. When I click price all the items between $10 - $50 sorted correctly but anything less than $10 and above $50 doesn't sort with them.

Here is my code:

class TeethersController < ApplicationController
  before_action :authenticate_user!,except: [:index,:show]
  helper_method :sort_column, :sort_direction
  before_action :find_teether, only: [:destroy,:edit,:update,:show]

  def index
    @teethers= Teether.all.order(sort_column + ' ' + sort_direction)
    @colors = Array.new
    @types = Array.new
    @teethers.each {|t| @types << t.types.pluck(:name) }
    @teethers.each {|t| @colors << t.colors.pluck(:name) }
    if params[:search]
      @search_term = params[:search]
      @teethers= @teethers.search_by(@search_term)
    end
    if params[:type_id]
      @types = Typation.where(type_id: params[:type_id])
      @teethers = @types.map(&:teether)
    end
  end

  def create
    @teether = Teether.new(teether_attributes)

    if @teether.save
      redirect_to teethers_path, notice: "Thank you... Your teether information was created successfully."
    else
      flash.now[:error] = "Please correct the form"
      render :new
    end
  end

  def new
    @teether=Teether.new 
  end
  private
  def find_teether
    @teether = Teether.find(params[:id])
  end

  def sort_column
    Teether.column_names.include?(params[:sort]) ? params[:sort] : "name"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end

  def teether_attributes
    teether_attributes = params.require(:teether).permit([:name,:description,:price,:image,:keywords,:status,:quantity,:discount,:kind,{type_ids: []},:gender,:color,:theme])
  end
end

My application helper is:

module ApplicationHelper
   def sortable(column, title = nil)
    title ||= column.titleize
    direction = (column == sort_column && sort_direction == "asc")? "desc" : "asc"
    link_to title, :sort => column, :direction => direction
  end
end

This is in my index:

<h3 id="sort"><label>Sort: </label><span> | </span><span><%= sortable "price" %><span class="caret"></span></span></h3>

In database

class CreateTeethers < ActiveRecord::Migration[5.2]
  def change
    create_table :teethers do |t|
      t.string :name
      t.text :description
      t.string :price

      t.timestamps
    end
  end
end


class AddDiscountToTeether < ActiveRecord::Migration[5.2]
  def change
    add_column :teethers, :discount, :text
    add_column :teethers, :kind, :text
  end
end

I checked out your website and I think your problem is that you are trying to sort price(string values) and this is causing problem. Let me try to explain it via this example.

arr = ['1', '45', '2', '100', '1001']

If you try to sort this array by this

arr.sort

it will give out this output ["1", "100", "1001", "2", "45"]

But if you use this kind of sort

arr.sort_by { |num| num.to_i }

it will give you something like this ["1", "2", "45", "100", "1001"]

In here depending on your preference you can use to_i, to_d or to_f methods

--------- After migration file is shared

You need to change text fields to decimal in your migration/schema.

class ChangeTeethersPriceAndDiscountToDecimal < ActiveRecord::Migration[5.2]
  def change
    change_column :teethers, :price, :decimal
    change_column :teethers, :discount, :decimal
  end
end

After that your code is going to sort them correctly

Change the price to decimal (or maybe integer... cents... and use "money" gem, it's a nice gem!).

I don't think a migration will let you change string to decimal but if this is a development that's not yet deployed and live, that shouldn't matter.

So, make a migration to remove_column 'value' and 'discount'

Then make a migration to add_column value as a decimal field, and discount as a decimal field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM