PJCHENder 未整理筆記

[Gem] Acts as taggable

2018-05-23

[Gem] Acts as taggable

@(Ruby on Rails)[rails, gem]

Install

1
2
3
4
# Gemfile

# With ActsAsTaggableOn, you can tag a single model on several contexts.
gem 'acts-as-taggable-on', '~> 6.0'
1
$ bundle

Post Install

1
2
# For the latest versions :
$ rake acts_as_taggable_on_engine:install:migrations

Model

1
2
3
4
5
# app/models/event.rb
class Event < ApplicationRecord
acts_as_taggable_on :genres # 如果不須保留 tags 的順序
acts_as_ordered_taggable_on :skills, :interests # 如果保留 tags 的順序
end

Controller

1
2
3
4
5
6
# app/controllers/event_controller.rb

# Never trust parameters from the scary internet, only allow the white list through.
def event_params
params.fetch(:event, {}).permit( :genre_list)
end

View

1
2
3
<!-- app/views/events/_form.html.erb -->
<% @genre_list = event.genre_list %>
<%= f.hidden_field :genre_list, 'data-target': 'form.taggable', value: '1, 2, 3' %>

產生出來的 HTML 會像這樣:

1
<input type="hidden" value="1, 2, 3" name="event[genre_list][]" id="event_genre_list" />

取得所有的 tags

1
2
3
event.all_tags_list
# 或
@tag_options = ActsAsTaggableOn::Tag.all.map { |tag| tag.name }

參考:How to get a list of all tags while using the gem ‘acts-as-taggable-on’ in Rails (not the counts) @ StackOverflow

Configuration

如果要加相關的設定,可以設在 config/application.rb 中:

參考:Where do I set the configuration options like ActsAsTaggableOn.remove_unused_tags = true @ Github Issue

資料來源

掃描二維條碼,分享此文章