Active Support コア拡張機能 - Railsガイド
Railsガイドに書いてあるサンプルを解釈してみる。
たとえば、UserモデルとProfileモデルがある。
- Userモデル
- Profileモデル
UserはひとつのProfileを持つ。
# id :integer not null, primary key # name :string # created_at :datetime not null # updated_at :datetime not null class User < ApplicationRecord has_one :profile end
# id :integer not null, primary key # age :integer # food :string # created_at :datetime not null # updated_at :datetime not null # user_id :integer not null class Profile < ApplicationRecord belongs_to :user end
もし、Userモデルのインスタンスから、Profileモデルの属性を取得したいとなったら、通常はこんな感じで取得するだろう。
user = User.find(id)
user.profile.food
user.profile.age
実はこれ、もっと短く書くことができる。そう、delegate
ならね。
class User < ApplicationRecord has_one :profile delegate :food, :age, to: :profile end
delegate :food, :age, to: :profile
と書くことで、以下のようにデータを取得できるようになる。
#変更前 user.profile.food user.profile.age #変更後 user.food user.age