LoginSignup
18
14

More than 5 years have passed since last update.

acts-as-taggable-on でモデルクラス毎に使用されているタグ一覧を取得する

Posted at

たとえば 店舗 Shop と 商品 Product があって、それぞれにタグを使用していたとき、店舗に割り当てられているタグのみを取得したいとき。

shop.rb
class Shop < ActiveRecord::Base
  acts_as_taggable_on :tags
  acts_as_taggable_on :genres
end
product.rb
class Product < ActiveRecord::Base
  acts_as_taggable
end

tags_on は acts_as_taggable_on/acts_as_taggable_on/collection.rb で クラスメソッドとしても用意されていて

Product.tags_on(:tags) # => ActiveRecord::Relation
Shop.tags_on(:tags)
Shop.tags_on(:genres)

のように取得することができる。(インスタンスメソッドの tags_on は配列を返すが、こちらは ActiveRecord::Relation を返す)

ちなみに、コンテキスト(:tags とか :genres)を指定せず、そのモデルクラスに使用されているもの全てを取り出すのであれば

Shop.all_tags # => ActiveRecord::Relation

で可能。

18
14
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
18
14