LoginSignup
9
11

More than 3 years have passed since last update.

ransackでラベル検索をチェックボックス検索にしたい

Last updated at Posted at 2020-02-10

Ransackを使ったラベル(label)検索をどうしてもチェックボックス(check_box)で実装したいことがあったのでメモ

スクリーンショット 2020-02-10 18.25.55.png

ラベル機能がある状態からスタート!!!
※ラベル機能の作成まではこの記事で完結できます↓
【gemなし】Railsでラベル機能を作る

gemのransackをインストール

rb.Gemfile
gem 'ransack'
$ bundle install
posts_controller.rb
  def index
    @search = Post.ransack(params[:q])
    @posts = @search.result(distinct: true)
  end


  private
    def post_params
      params.require(:post).permit(:title, :details, label_ids: [] )
    end
view.posts.index.html.erb
<%= search_form_for @search do |f| %>
  <% Label.all.each do |label| %>
    <%= f.check_box :labels_id_eq_any, { multiple: true, checked: label[:checked], disabled: label[:disabled], include_hidden: false }, label[:id] %>
    <label><%= label.title %></label>
  <% end %>
  <%= f.submit "検索" %>
<% end %>

以上です!

参考記事
https://www.tom08.net/entry/2016/11/11/144813

9
11
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
9
11