u16suzuの blog

日々学んだことのメモブログです。

ARのrelationのメソッド定義

Association extensions

# Post::ActiveRecord_Associations_CollectionProxy に hoge メソッドを生やす.
# 当然メソッド内でのselfはPst::ActiveRecord_Associations_CollectionProxyで posts が入っている。
# CollectionProxyに生えているので 当然 Post.first.hoge ではよべない.
# posts.hoge でだけcall可能
# 引数で値を取れる。自分の値は取れないらしい。  
has_many :posts do
  def hoge(title)
    p title
    p self.class
  end
end

Extending

module を使って共通化できる

module Foo
  def foo_method
  end
end

class Category < ApplicationRecord
  has_many :foo, -> { extending Foo }, class_name: "Post", foreign_key: "category_id"
end