数分できたので多分最高にシンプル。
コントローラにクラスメソッド追加。
def index @commands = Pipe.search(params[:q]).paginate(page: params[:page]) end
モデルにロジック記述。ポイントはCase insensitiveにしているところとOR検索してるところ。
def self.search(query) if query.present? q = query.downcase Pipe.where('lower(title) LIKE ?', "%#{q}%").or(Pipe.where('lower(line) LIKE ?', "%#{q}%")) else Pipe.all end end
Viewはこんな感じ。
<%= form_with(url: '/cmds', method: 'get', local: true) do %> <%= text_field_tag(:q, "", class: "uk-input uk-form-width-medium") %> <%= submit_tag("Search", class: "uk-button uk-button-default") %> <% end %>