0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsのdelegateをざっくり理解する

0
Posted at

はじめに

Railsでコードを書いていると、関連先のオブジェクトが持っている値を取りたくなることがあります。

たとえば、UserProfile を持っていて、プロフィールの名前を取得したいとします。

user.profile.name

このように書けますが、毎回 profile を経由して呼ぶのが少し長く感じることもあります。

そんなときに使えるのが delegate です。

delegateとは

delegate は、別のオブジェクトのメソッドを、自分のメソッドのように呼べるようにするものです。

基本形

class User < ApplicationRecord
  has_one :profile

  delegate :name, to: :profile
end

これは「nameprofile に委譲する」という意味です。

もともとは user.profile.name と書いていたものを、user.name と書けるようになります。

複数まとめて書く

delegate :name, :age, to: :profile

複数のメソッドをまとめて書くこともできます。

prefixをつける

delegate :name, to: :profile, prefix: true

この場合は、 user.name ではなくuser.profile_name と書くようになります。

nilでもエラーにしない

delegate :name, to: :profile, allow_nil: true

この場合は、profile がないときでもエラーにならず nil を返します。

最後に

Railsを書いているとたまに見かけるので、まずは「呼び出しをシンプルにするためのもの」くらいで覚えておくとよさそうです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?