pg_search_scope不按desc或asc排序

时间:2018-12-24 14:16:14

标签: ruby-on-rails ruby

我有一个小问题。而且不知道如何解决。

我希望在通过pg_search_scope过滤后,我可以单击时按升序和降序进行排序。 如果我尝试不使用搜索进行排序,则一切正常,但是,如果我使用搜索(在trucks_controller中查找是否params [:q] .present?),则不起作用:(

model / truck.rb

class Truck < ApplicationRecord
  include PgSearch

  pg_search_scope :search,
              against: [:name],
              using: {
                tsearch: {
                  prefix: true,
                  any_word: true
                }
              }

 #Associations
  belongs_to :company
  has_many :crews

  #Validations
  validates_presence_of :name, :company
  validates_uniqueness_of :name, scope: [:company]
end

trucks_controller.rb

class TrucksController < ApplicationController
  before_action :load_truck, only: [:update, :destroy, :show]
  before_action :load_search_trucks, only: :index

  def index
    paginate json: @trucks, status: :ok, per_page: 10
  end

  private

  def load_search_trucks
    if params[:q].present?
      @trucks = current_company.trucks.search(params[:q]).order_by(params[:sort_by], params[:direction])
    else
      @trucks = current_company.trucks.order_by(params[:sort_by], params[:direction])
    end
  end
end

0 个答案:

没有答案