はじめに
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
参考