首页 > 解决方案 > pg_search_scope 不按 desc 或 asc 排序

问题描述

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

我希望在通过 pg_search_scope 过滤后,单击时可以按升序和降序排序。如果我尝试不使用搜索进行排序,一切正常,但如果我使用搜索(查看 if params[:q].present? at trucks_controller)它就不行了:(

型号/卡车.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

卡车控制器.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

标签: ruby-on-railsruby

解决方案


推荐阅读