LoginSignup
1

posted at

Railsに簡単な検索フォームを作ってみた(Ransack)

自分の作成している掲示板サイトに簡単な検索フォームを作りたいと考え、Ransackというgemを使い、記事を参考にしながら作成しました。

参考記事
https://www.sejuku.net/blog/100824

環境とver
ruby '2.7.5'
rails '6.1.4'
Docker

github
https://github.com/takoyan33/railsdock4

まず最初に

Gemfile
gem 'ransack'
#ransackを追加
ターミナル
bundle install
#dockerの場合、docker-compose run web bundle install

これでransackを入れることができました。
次にコントローラーに記述します。
自分の場合、kaminariのgemを入れているのと、降順に表示したいので、
色々後ろについています。
普通に追加する場合は、.page(params[:page]).per(8).all.order(id: "DESC")の後ろは消して大丈夫です。
(良い書き方があれば教えてほしいです。)

boards_controller.rb
 def index
    @boards = params[:tag_id].present? ? Tag.find(params[:tag_id]).boards : Board.all.order(id: "DESC") 
    @boards_count = Board.all.count
    @today_count = Board.created_today.count
    @lastmonth_count = Board.created_last_month.count
    @month_count = Board.created_month.count

    @q = Board.ransack(params[:q])#追加
    @boards = @q.result(distinct: true).page(params[:page]).per(8).all.order(id: "DESC") #追加
  end

そして、viewに表示していきます。
ここでポイントは検索したい値を書くことです。
自分の場合は、掲示板(board)のタイトルを検索したいので、
:title_count にしています!(contは部分一致で表示してくれます。)
そのため、例えば投稿(post)の名前(name)で検索したい場合は、name_contなどにしましょう。

index.html.erb
    <%= search_form_for @q do |f| %>
        <%= f.search_field :title_cont %>
        <%= f.submit %>
    <% end %>

これで完成です。
※デザインは雑です。

スクリーンショット 2022-04-26 20.23.33.png
スクリーンショット 2022-04-26 20.23.45.png

慣れると使いやすいGemなどでぜひ一度使ってみてください。

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
What you can do with signing up
1