Rails 委譲(delegation) delegateについて

メソッドチェーンをたくさん書くことなく実装できる。
書き方の例は以下の通り。

delegate :method_name, to: :associtation

具体例は以下の通り。
Userモデルにログイン情報があり、関連する名前などはProfileモデルにあるとした場合。

delegate を使った場合

class User < ApplicationRecord
  has_one :profile

  delegate :name, to: :profile
end
# userに紐づいたProfileモデルにあるnameを取得する
user.name
# 通常であれば以下のように取得する
user.profile.name


delegateを使わなかった場合

class User < ApplicationRecord
  has_one :profile

  def name
    profile.name
  end
end

詳細情報はRailsガイドを参照


この記事が気に入ったらサポートをしてみませんか?