From dea3c8e294018eaf8a1f4e2b063470a482a097f9 Mon Sep 17 00:00:00 2001 From: Ted Date: Mon, 23 May 2022 14:01:37 +0100 Subject: [PATCH] Refactored to scope --- app/controllers/organisations_controller.rb | 11 +---------- app/controllers/users_controller.rb | 11 +---------- app/models/user.rb | 3 +++ 3 files changed, 5 insertions(+), 20 deletions(-) diff --git a/app/controllers/organisations_controller.rb b/app/controllers/organisations_controller.rb index e05b600ca..f0c2dcbfd 100644 --- a/app/controllers/organisations_controller.rb +++ b/app/controllers/organisations_controller.rb @@ -17,7 +17,7 @@ class OrganisationsController < ApplicationController end def users - @pagy, @users = pagy(filtered_users) + @pagy, @users = pagy(User.filter_by_name(params["user-search-field"]).filter_by_active) render "users/index" end @@ -58,15 +58,6 @@ class OrganisationsController < ApplicationController private - def filtered_users - search_param = params["user-search-field"] - if search_param - User.where("name ILIKE ?", "%#{search_param}%").where(active: true) - else - User.all.where(active: true) - end - end - def org_params params.require(:organisation).permit(:name, :address_line1, :address_line2, :postcode, :phone) end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 067d27c48..0640fbf18 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -9,7 +9,7 @@ class UsersController < ApplicationController def index redirect_to users_organisation_path(current_user.organisation) unless current_user.support? - @pagy, @users = pagy(filtered_users) + @pagy, @users = pagy(User.filter_by_name(params["user-search-field"]).filter_by_active) respond_to do |format| format.html @@ -77,15 +77,6 @@ class UsersController < ApplicationController private - def filtered_users - search_param = params["user-search-field"] - if search_param - User.where("name ILIKE ?", "%#{search_param}%").where(active: true).includes(:organisation) - else - User.all.where(active: true).includes(:organisation) - end - end - def format_error_messages errors = @user.errors.to_hash @user.errors.clear diff --git a/app/models/user.rb b/app/models/user.rb index f32096ad6..2cae675ad 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -32,6 +32,9 @@ class User < ApplicationRecord enum role: ROLES + scope :filter_by_name, ->(name) { name.present? ? where("name ILIKE ?", "%#{name}%") : User.all } + scope :filter_by_active, ->() { where(active: true) } + def case_logs if support? CaseLog.all