Search code examples
ruby-on-railslaw-of-demeter

How to apply law of demeter in a rails for loop


I've got a rails app that has a Users model that have one User_profile. When I want to show multiple users on a page i use a rails loop like:

<% @users.each do |user| %>
  <%= user.user_profile.city %>
<% end %>

Which shows the users city of residence. However this is does not follow the law of demeter (or so the jenkins build on my bitbucket tells me). I could make a city scope on my User model so that i could call user.user_profile_city, but I don't know if this is the best way to solve this since i would have to do this for every user_profile attribute (which kind of makes the user_profile table useless). What is the Rails way to solve this?


Solution

  • You don't need to add a scope, you can use delegate. Add this to your User model:

    delegate :city, to: :user_profile
    

    and then your view becomes

    <% @users.each do |user| %>
      <%= user.city %>
    <% end %>
    

    Check http://api.rubyonrails.org/classes/Module.html#method-i-delegate for more details.