Sherwyn Cooper
Sherwyn Cooper

Reputation: 9

DRY ruby on rails loops

I am trying to loop through my users and sum an attribute act_points from associated post_activites and then assign and save it to my users table attribute total_points. The code below works for me but it doesn't follow DRY.

<% @users.order("total_points desc").each do |u| %> 
  <p><% u.total_points = u.post_activities.sum(:act_points).round(2) %> </p>
  <% u.total_points %>
  <% u.save %>
<%end%>
<% @users.order("total_points desc").each do |u| %> 
  <p><% u.total_points = u.post_activities.sum(:act_points).round(2) %> </p>
  <%= u.total_points %>
<%end%>

Any suggestions on how to combine these loops or shorten them?

Upvotes: 0

Views: 101

Answers (1)

hedgesky
hedgesky

Reputation: 3311

You can refactore your code in this way:

# user.rb
def actual_points
  post_activities.sum(:act_points).round(2)
end

def update_total_points
  update(total_points: actual_points)
end

# in controller (change index to your method)
def index
  @users = User.order("total_points desc")
  @users.find_each do |user|
    user.update_total_points
  end
end

# view
<% @users.each do |u| %> 
  <%= u.total_points %>
<%end%>

Upvotes: 3

Related Questions