我想让我的代码简单有效。我的代码是这样的(在MODEL中)
class Employee < ApplicationRecord
mount_uploader :image, AvatarUploader
def self.search(search)
if search
where(('(name LIKE ? OR name = ?) AND (employee_type = "SE" OR employee_type = "OP")'), "%#{search}%", "")
else
unscoped
end
end
end
我的控制器是这样的:
class EmployeesController < ApplicationController
before_action :set_employee, only: [:show, :edit, :update, :destroy]
# GET /employees
# GET /employees.json
helper_method :sort_column, :sort_direction
def index
@employees = Employee.all
@employees = Employee.search(params[:employee_type])
@employees = Employee.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 5, :page => params[:page])
end
end
答案 0 :(得分:1)
你可以从做这样的事情开始
class EmployeesController < ApplicationController
before_action :set_employee, only: [:show, :edit, :update, :destroy]
# GET /employees
# GET /employees.json
helper_method :sort_column, :sort_direction
def index
if params[:employee_type].present?
@employees = Employee.search(params[:employee_type])
elsif params[:search].present?
@employees = Employee.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 5, :page => params[:page])
else
@employees = Employee.all
end
end
end
现在你不会超越你的变量