DEV Community

Nesha Zoric
Nesha Zoric

Posted on

6 1

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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay