When to use a delegate and when to use has_one: through?

Rails has two great ways to avoid breaking Demeter’s law in models.

The first is:

class Restaurant < ActiveRecord::Base
    belongs_to :franchise
    delegate :owner, to: :franchise
end

The second is the following:

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 another in some or all cases?

The only difference I can find is that the option delegateseems to generate two SQL queries to retrieve the last record, while it belongs_to :throughseems to do this in one query.

+4
source share
1 answer

has_one through: - - , join , , N+1 Restaurant s

Restaurant.all.includes(:owner).each{|r| some code accessing r.owner }

owner , ( .includes), Restaurant ,

+5

Source: https://habr.com/ru/post/1624242/


All Articles