2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

delegateメソッドとは

Posted at

delegateメソッドとは

メソッドを簡単に委譲できるメソッド。

例えば、Userモデルログイン情報があり、それに関連する名前などの情報はProfilemモデルがあったとする。

model/user.rb
class User < ApplicationRecord
  has_one :profile
end

profileの中にある、name要素を取り出したい時、user.profile.nameのようにメソッドチェーンしたものを書く。

しかし毎回メソッドチェーンしたものを呼び出すのも面倒なので、
user.nameにしたい。そんな時にdelegateを使う。

なお下記はdelegateを使用しない場合の記述。

model/user.rb
class User < ApplicationRecord
  has_one :profile
 
  def name
    profile.name
  end
end

使い方

delegate :メソッド名カラム名, to: :関連付けしているモデル名
model/user.rb
class User < ApplicationRecord
  has_one :profile
 
  delegate :name, to: :profile
end

delegateには複数のメソッドを指定できる。

#基本の型
delegate :name, :age, :address, :twitter, to: :profile

オプション

prefix
delegateはパブリックメソッドとして定義するので、もし重要なデータなどを指定してしまうと、可能性として低いが面倒なことが起きることもあるので、privateメソッドとしてdelegateを定義することが可能になっている。

delegate :date_of_birth, to: :profile, private: true

↑上記と同義になり、アクセスできる範囲を狭めることが可能。

private

def date_of_birth
  user.date_of_birth
end

allow_nil
:allow_nilオプションを付与すると、profilenilだった場合に、user.nameは例外ではなく、nilを返すようにできる。

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

下記のようにぼっち演算子をつけたメソッドを定義したものと同義になる。

def name
    profile&.name
  end

参考記事

Railsガイド
【Ruby on Rails】delegateの使い方【委譲は便利】
【Rails】delegateで省エネする方法を、公式リファレンスから理解する

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?