[gem] Acts as list
Install
# Gemfile
# With ActsAsTaggableOn, you can tag a single model on several contexts.
gem 'acts-as-taggable-on', '~> 6.0'
$ bundle
Post Install
# For the latest versions :
$ rake acts_as_taggable_on_engine:install:migrations
Model
# app/models/event.rb
class Event < ApplicationRecord
acts_as_taggable_on :genres # 如果不須保留 tags 的順序
acts_as_ordered_taggable_on :skills, :interests # 如果保留 tags 的順序
end
Controller
# 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
<!-- 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 會像這樣:
<input type="hidden" value="1, 2, 3" name="event[genre_list][]" id="event_genre_list" />
取得所有的 tags
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
資料來源
- Acts as taggable @ Github