LoginSignup
5
3

More than 5 years have passed since last update.

acts-as-taggable-onをcheckboxで操作する

Last updated at Posted at 2018-09-02

Railsでタグ作成に重宝するacts-as-taggable-onというGemがあります。
が、基本的には
Vegewel見てね
こんなような手で入力するフィールドに打ち込むというシーンを想定して使っていると思います。
これが、
Vegewel見てね
こんなふうに入力できたら便利ですよね?

あまりネット上に情報がないのと、本家のGemのサイト
https://github.com/mbleigh/acts-as-taggable-on
にも出てなかったのでこちらにやり方を載せておきます。

基本的にGemをBundleしてテーブルを作成し、ModelとController作るところまでは一緒です。
端折ってしまうと不親切かなと思うので念の為書いておくと、

Gemfileに以下を記載

gem 'acts-as-taggable-on', '~> 6.0'

Bundleを実行

$ bundle

Tag関連テーブルの作成

$ rake acts_as_taggable_on_engine:install:migrations
$ rake db:migrate

Model

基本的に使う側(今回でいうとRestaurant)のModelにacts_as_taggable_onを記載する。
今回はタグに名前をつけているので以下のような表記になっているがacts_as_taggableだけしか書かないとデフォルトはtagという名称になる。

restaurant.rb
    class Restaurant < ActiveRecord::Base
      acts_as_taggable_on :cuisines

Contoroller

ストロングパラメータにも記載。今回cuisineの名称をつけているので変数としてはcuisine_listとなる。
配列で定義するのでパラメータの後ろの方に記述する。コロンの位置にも注意。

restaurant_controller.rb

    def restaurant_params
      params.require(:restaurant).permit(
        :id, :other,
        cuisine_list: []
      )

View

ここからがあまり情報が出てないところ。ul, liで作成したリストで出す場合の例となる。
今回はCuisineというモデル全件出してその中でcuisine_listに含まれているものがあればチェックを入れるという作りとなっているのでこのような表記になる。
さらにもう一点重要なポイントだが、 labelタグとその後に続くinputタグのidの名称を合わせないとIE11とFirefoxでチェックボックスが動かないという問題があるのでここを合わせる必要がある。何かおかしいと思ったらinputタグのid属性を確認するのをおすすめする。

restaurant/create.rb
          ul.field.option_check
            - Cuisine.all.each do |cuisine|
              li
                label for="restaurant_cuisine_list_#{cuisine.id.to_s}"
                  = r.check_box :cuisine_list, {multiple: true, checked: @restaurant.cuisine_list.include?(cuisine.id.to_s)}, cuisine.id.to_s, ''
                  span.checkbox =  cuisine.cuisine_name

ちなみにここはslimで書いた場合の例なので他のテンプレートエンジン使っている場合は適宜読み替えてください。

5
3
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
5
3