0
0

【Rails】delegateの使い方

Last updated at Posted at 2023-10-14

はじめに

Railsで便利な書き方をおしえてもらったので記録に残します。

やりたいこと

usersテーブルとuser_profilesテーブルが存在
一対一の関係。
Userクラスからuser_profilesのnameカラムを参照したい場合に
、最初は以下の書き方をしていました。

user.rb
class User < ApplicationRecord
  has_one :user_profile
 
  def name
    user_profile.name
  end
end
sample.rb
# 以下でよびだせる
@user = User.new
@user.name

結論

user.rb
class User < ApplicationRecord
  has_one :user_profile
 
  delegate :name, to: :user_profile
end
sample.rb
# 以下でよびだせる
@user = User.new
@user.name

呼び出したいカラムが複数あっても一行で済むのでめちゃ便利ですね!

おまけ

じつは、decoratorで、すでに似たようなことをしていましたね。
delegate_allでモデルのメソッドを呼び出せます。
delegateとは、ざっくり委譲するという意味だそうです。

decorator.rb
class UserDecorator < ApplicationDecorator
  delegate_all
end

参考

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