Rails Best PracticesのLaw of demeterを直してる時に結構出てくる。

class Award < ActiveRecord::Base
  belongs_to :story
  delegate :user, :user_name, to: :story, prefix: true
end

class Story < ActiveRecord::Base
  belongs_to :user
  delegate :name, to: :user, prefix: true
  
  has_many :awards
end

class User < ActiveRecord::Base
  has_many :stories
end
>> Award.find(1).story_user_name # => "komagata"

これは分かりやすくなってる!・・・のかな・・・。

Comments


(Option)