以下のような投稿とタグの関係を考える.一部のタグはデフォルトで見えないようにするために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_many
のconditions
オプションを使う.
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 を.