0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ransackを使う

Posted at

内容

gem ransackを使って検索機能を実装する方法を記述

ransackをインストールする

Gemfileにransackを記述

gem 'ransack'

ターミナルにて

$ bundle install

※サーバーを再起動する

検索したいcontrollerにて

def index
  @q = Question.ransack(params[:q])
  @questions = @q.result(disitinct: true)
end

html.erbにて

<%= search_form_for @q do |f| %>

  <%= f.label :title_cont %>
  <%= f.search_field :title_cont %>

  <%= f.submit %>

今回の場合は_contを使用(入力した文字を含んでいるもの)

参考
https://github.com/activerecord-hackery/ransack

Image from Gyazo

内容でも検索したい

以下のような投稿の時にタイトルだけでなくbodyの内容も検索に引っ掛けたい
Image from Gyazo

<%= search_form_for @q do |f| %>

  <%= f.label :title_cont %>
  <%= f.search_field :title_or_body_cont %>

  <%= f.submit %>
<% end %>

のようにorを使うと

Image from Gyazo
検索に該当することができる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?