DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Nesha Zoric
Nesha Zoric

Posted on

Delegate in Rails

A model should only talk to its immediate association. According to the Law of Demeter, you shouldn’t talk to the association’s property or association’s association.

Here we talk about Rails delegate approach.

BAD SMELL

class Profile < ActiveRecord::Base
belongs_to :user
end

<%= @profile.user.address %>
<%= @profile.user.city %>

Rails provides helper method to accomplish delegation, which uses DSL to generate wrapper methods. It can also prevent error call method on nil object if :allow_nil => true is added.

Refactored

class Profile < ActiveRecord::Base
  belongs_to :user
  delegate :address, :city, :to => :user, :prefix => true, :allow_nil => true
end
<%= @profile.user_address %>
<%= @profile.user_city %>

Originally published at Kolosek blog.

Top comments (0)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another β€œCoder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.