LoginSignup
2
1

More than 3 years have passed since last update.

Ransackでor検索機能を作る。

Posted at

使用環境

rails 6.0.2
ubuntu (WSL)

手順

gemインストール

gem 'ransack'

bundleを忘れずに。

内容の検索

post_controllerは既に作ってあるものとします。

posts_controller.rb
  def index
    unless params[:q].blank?
       #入力された単語を空白で分割
      split_keyword = params[:q][:content_cont].split(/\p{blank}/)
    end
    @q = Post.ransack(content_cont_any: split_keyword)
    @posts = @q.result
  end

入力(検索ワード)があるか調べる。
ここがないとエラーになると思う。

unless params[:q].blnak?

検索フォーム

posts/index.html.slim
 = search_form_for @q, class: 'mb-5 search-container' do |f|
   .form-group.row
     = f.search_field :content_cont, placeholder: "キーワードを入力してください", class: "form-control"
     = f.submit class: "btn btn-outline-primary"

2
1
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
2
1