LoginSignup
5
5

More than 5 years have passed since last update.

デフォルトスコープとHABTM(has_and_belongs_to_many) relations

Last updated at Posted at 2013-04-03

以下のような投稿とタグの関係を考える.一部のタグはデフォルトで見えないようにするためにdefault_scopeを使ってみる.

models
class Tag < ActiveRecord::Base
  default_scope private: false
end
class Item < ActiveRecord::Base
  has_and_belongs_to_many :tags, join_table: "taggings"
end

しかしこうするとitem.tagsでprivate tagsを取ってこれない.

間違った対応

最初は以下のようにしていたが,これではセッター(item.tags = tagsなど)のときには問題が起きる.例えばitem.tags.push(tag)などとしても保存されなかったりする.わかりづらい.

item.rb
class Item < ActiveRecord::Base
  # ...
  protected
  def tags_with_unscoped
    Tag.unscoped { tags_without_unscoped }
  end
  alias_method_chain :tags, :unscoped
end

正しい方法

has_and_belongs_to_manyconditionsオプションを使う.

item.rb
class Item < ActiveRecord::Base
  has_and_belongs_to_many :tags, join_table: "taggings", conditions: { tags: { private: [true, false] }}
end

associationについては Ruby on Rails Guides: A Guide to Active Record Associations を.

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