delegate を、直接のリレーションを持たない孫モデルに定義する方法についてまとめます。
例: 以下の状況で、Company の address カラムを Profile で呼び出したいとき、
class Company < ApplicationRecord
has_one :user
end
class User < ApplicationRecord
belongs_to :company
has_one : profile
end
class Profile < ApplicationRecord
belongs_to :user
end
User と Profile に以下のように delegate を定義することで、Profile から address が呼び出せるようになります。
class User < ApplicationRecord
belongs_to :company
has_one : profile
+
+ delegate :address, to: :company
end
class Profile < ApplicationRecord
belongs_to :user
+
+ delegate :address, to: :user
end
prefix: true をつけることでメソッドを一意に指定することができますが、孫モデルに当たる Profile では prefix がついた後の company_address を指定しないといけないことに注意が必要です。
class User < ApplicationRecord
belongs_to :company
has_one : profile
- delegate :address, to: :company
+ delegate :address, to: :company, prefix: true
end
class Profile < ApplicationRecord
belongs_to :user
- delegate :address, to: :user
+ delegate :company_address, to: :user, prefix: true
end
これによって、profile.user_company_address のようにアクセスすることができます。