Rails has two nice ways to avoid Law of Demeter violations in models.
The first is this:
class Restaurant < ActiveRecord::Base
belongs_to :franchise
delegate :owner, to: :franchise
end
The second is this:
class Restaurant < ActiveRecord::Base
belongs_to :franchise
has_one :owner, through: :franchise
end
What is the difference? Is there anything to recommend one option over the other in some or all instances?
The only difference I can detect is that the delegate
option seems to generate two SQL queries to get at the latter record, whereas belongs_to :through
seems to do it in one query.