スコープ 関連先を取得する際に追加の条件を付与する
使用可能な関連付け
belongs_to
has_and_belongs_to_many
has_many
has_one
概要
関連先を取得する際に追加の条件を付与する。
class Author < ApplicationRecord
has_many :books, -> { where(published: true) }
end
各関連メソッドは、第二引数に追加で絞り込む条件を指定できる。上記のような指定をするとauthor.books
を実行した際にauthor.books.where(published: true)
を実行したのと同じ結果を返すようになる。
belongs_to
にも指定可能だが、関連先が未保存だと常にバリデーションエラーになってしまうので注意が必要である。
class Book < ApplicationRecord
belongs_to :author, -> { where(anonym: false) }
end
author = Author.create(books: [Book.new])
uthor.books.last.errors.full_messages
# => ["Author must exist"]
# こっちの場合は問題ない
Book.create(author: Author.new)