やりたいこと
Officeテーブルにあるカラムでフリーキーワード検索したいと考えています。
複数カラムキーワード検索したいのですが、
- name
- address
- near_station
- introduction
- company
これらのカラムで入力されたキーワードに該当するOfficeを取得したいです。
Officesコントローラーのsearchアクションの記述の方法がわかりません。
詳しい方、ご教授お願い致します。
コード
class OfficesController < ApplicationController include Pagy::Backend def index pagy, offices = pagy(Office.all) pagy_headers_merge(pagy) render json: offices, each_serializer: OfficeIndexSerializer, include: '**' end def show office = Office.find(params[:id]) render json: office, serializer: OfficeShowSerializer, include: '**' end def search if params[:city_id] offices = Office.where(city_id: params[:city_id]) elsif params[:name, :near_station] offices = Office.where('name LIKE ?', "%#{params[:name]}%", 'address LIKE ?', "%#{params[:address]}%", 'near_station LIKE ?', "%#{params[:near_station]}%", 'introduction LIKE ?', "%#{params[:introduction]}%", 'company LIKE ?', "%#{params[:company]}%" ) else pagy, offices = pagy(Office.all) end render json: offices end end
# frozen_string_literal: true Rails.application.routes.draw do get '/offices', to:'offices#index' get '/offices/search', to:'offices#search' # get '/offices/keyword', to:'offices#keyword' get '/offices/:id', to:'offices#show' get 'cities', to:'cities#get' mount_devise_token_auth_for 'User', controllers: { registrations: 'users' } devise_scope :user do get 'signin' => 'devise_token_auth/sessions#new' post 'signin' => 'devise_token_auth/sessions#create' post 'signup' => 'users#create' put 'update' => 'users#update' end get 'users/bookmarks', to: 'bookmarks#index' post '/users/bookmarks', to: 'bookmarks#create' delete '/users/bookmarks', to: 'bookmarks#destroy' get 'users/thanks/new', to: 'thanks#new' get 'users/thanks', to: 'thanks#index' post '/users/thanks', to: 'thanks#create' delete '/users/thanks', to: 'thanks#destroy' put '/users/thanks', to: 'thanks#update' #予約している日付の一覧を返す get '/reserve', to: 'reservations#index' #予約を作成する post '/reserve', to: 'reservations#create' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
# frozen_string_literal: true class CreateOffices < ActiveRecord::Migration[6.0] def change create_table :offices do |t| t.string :login_id t.string :password t.string :name t.string :title t.string :postcode t.string :address t.string :near_station t.string :tel t.string :fax t.string :email t.string :office_type t.string :opening_date t.string :room_number t.string :requirement t.string :facility t.string :company t.text :url t.text :introduction t.integer :staff_number t.references :city, foreign_key: true t.timestamps end end end
あなたの回答
tips
プレビュー