前提
フォームで入力された条件で、レコードの検索をかけるときにフォームの各項目に値があるかどうかでwhere文が変わります。
当初は、各項目を必須にすることはできないため、すべてのwhere文でワイルドカードであいまい検索を行っていました。
そうすると、処理が重くなってしまうため各項目の有無によってwhere文をわけるようにしました。
フォーム内容を必須にすることは考えていません。
実現したいこと
もう少し、簡潔に記述できるのではないかと思っているのですが、その方法があれば教えていただきたいです。
該当のソースコード
/model/history.rb
ruby
1def self.find_records(params) 2 logger.info(params) 3 4 shop_name = params[:shop].present? ? params[:shop] : '' 5 start_time = params[:start_time] 6 end_time = params[:end_time] 7 first_name = params[:first_name].present? ? params[:first_name] : '' 8 last_name = params[:last_name].present? ? params[:last_name] : '' 9 status = params[:status].present? ? params[:status] : '' 10 11 production_flg = (params[:first_name].present? && params[:last_name].present?) == true ? true : false 12 13 # shop_id、status、prodction 14 if shop_id != '' && status != '' && production_flg 15 record = 16 self.joins(:shop, :production) 17 .select('histories.*, productions.first_name, productions.last_name, shops.name') 18 .where("first_name = ?", "#{first_name}") 19 .where("last_name = ?", "#{last_name}") 20 .where("name = ?", "#{shop_name}") 21 .where("status = ?", "#{status}") 22 .where("start_time BETWEEN '#{start_time}' and '#{end_time}'") 23 .order("start_time") 24 # shop_id, status 25 elsif shop_id != '' && status != '' 26 record = 27 self.joins(:shop, :production) 28 .select('histories.*, productions.first_name, productions.last_name, shops.name') 29 .where("first_name LIKE ?", "%#{first_name}%") 30 .where("last_name LIKE ?", "%#{last_name}%") 31 .where("name = ?", "#{shop_name}") 32 .where("status = ?", "#{status}") 33 .where("start_time BETWEEN '#{start_time}' and '#{end_time}'") 34 .order("start_time") 35 # shop_id 36 elsif shop_id != '' 37 record = 38 self.joins(:shop, :production) 39 .select('histories.*, productions.first_name, productions.last_name, shops.name') 40 .where("first_name LIKE ?", "%#{first_name}%") 41 .where("last_name LIKE ?", "%#{last_name}%") 42 .where("name = ?", "#{shop_name}") 43 .where("status LIKE ?", "%#{status}%") 44 .where("start_time BETWEEN '#{start_time}' and '#{end_time}'") 45 .order("start_time") 46 else 47 record = 48 self.joins(:shop, :production) 49 .select('histories.*, production.first_name, production.last_name, shops.name') 50 .where("first_name LIKE ?", "%#{first_name}%") 51 .where("last_name LIKE ?", "%#{last_name}%") 52 .where("name LIKE ?", "%#{shop_name}%") 53 .where("status LIKE ?", "%#{status}%") 54 .where("start_time BETWEEN '#{start_time}' and '#{end_time}'") 55 .order("start_time") 56 end 57 return record 58 end 59
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。