The Law of Demeter for Ruby on Rails
According to the law of demeter, a model should only talk to its immediate association, don’t talk to the association’s association and association’s property, it is a case of loose coupling.
Bad Smell
class Invoice < ActiveRecord::Base
belongs_to :user
end
<%= @invoice.user.name %>
<%= @invoice.user.address %>
<%= @invoice.user.cellphone %>
In this example, invoice model calls the association(user)’s property(name, address and cellphone), which violates the law of demeter. We should add some wrapper methods.
Read on →