Delegated Type == Polymorphic Relation + 便利メソッドたち
Published: 2023/3/29
Rails 6.1 から Delegated Type が導入された。 これの正体は、 Polymorphic Relation に諸々の便利メソッドを生やすだけのものであったので、その備忘録。
DelegatedType の実装
rails/delegated_type.rb at 7c70791470fc517deb7c640bead9f1b47efb5539 · rails/rails
Ruby on Rails. Contribute to rails/rails development by creating an account on GitHub.
github.com
上記が、現行の Delegated Type の実装であって、コードを抜粋すると以下の通りになっている。
def delegated_type(role, types:, **options)
belongs_to role, options.delete(:scope), **options.merge(polymorphic: true)
define_delegated_type_methods role, types: types, options: options
end
define_delegated_type_methods
は、与えられた引数を元に、 scope
定義と define_method
をしているだけのヘルパー的な関数である。
よって、 Delegated Type でできることは、基本的には Polymorphic Relation でできたことと同義であって、 boilerplate なコードが減っただけ、というのが実態である。
Tags: rails
関連記事
Rails の view では、相対パス(キー)のロケールが使える
2023/9/7
(Rails) Controller 等で helper を呼ぶ方法
2023/6/15
factory_bot と必須 association
2023/4/23
Rails とタイムゾーン
2023/4/19