1

I'd like to make my code much simply and efficient. My code goes like this (in 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

and my controller goes like this:

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
8
  • @xdazz thanks dude! Commented Feb 20, 2017 at 2:25
  • it looks like you are over riding your variable in the controller @employees 3 times Commented Feb 20, 2017 at 2:27
  • @MZarogaza Ah I see. I'm just new in RoR :D Commented Feb 20, 2017 at 2:29
  • what is the end goal Commented Feb 20, 2017 at 2:30
  • What is it that you want to do? Commented Feb 20, 2017 at 2:32

1 Answer 1

1

Wou can start by doing something like this

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

now you wont over ride your variables

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

2 Comments

Thanks @Mzaragoza! I didn't know we can put conditional statements in controller :D Thanks!
@reynantedaitol I am glad to help :)

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.