extend 関連のCollectionProxyにメソッドを追加する
使用可能な関連付け
has_many
対となる関連に指定するオプション
なし
概要
基本的にExtensionsと同じなので、まずはそちらを参照してほしい。
Extensionsでは関連メソッドにブロックを渡していたが、同じ内容をmoduleで定義してextend
オプションに指定するという方法もある。
module ExtendBooks
def build_by_author
author = proxy_association.owner
build(title: "#{author.name}の本(仮題)")
end
end
class Author < ApplicationRecord
has_many :books, extend: ExtendBooks
end