Extensions 関連のCollectionProxyにメソッドを追加する
使用可能な関連付け
has_and_belongs_to_many
has_many
概要
特定の関連の場合のみCollectionProxyにメソッドを追加する。
class Author < ApplicationRecord
has_many :books do
def build_by_author
author = proxy_association.owner
build(title: "#{author.name}の本(仮題)")
end
end
end
Author.create(name: '鈴木')
book = Author.last.books.build_by_author
book.title # => "鈴木の本(仮題)"
上記の例のように、has_many
にはブロックを渡すことができる。このブロックの中でメソッドを定義すると、CollectionProxyにメソッドを追加することができる。
ブロックで定義しているメソッドのレシーバはCollectionProxy(books
の例ならBook::ActiveRecord_Associations_CollectionProxy
)になり、関連元を参照するにはproxy_association.owner
から取得する必要がある。
ブロックではなく、Moduleを定義してCollectionProxyを拡張する方法もある。extendオプションを参照。