DRY ruby on rails loops -
i trying loop through users , sum attribute act_points
associated post_activites
, assign , save users table attribute total_points
. code below works me doesn't follow dry.
<% @users.order("total_points desc").each |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 |u| %> <p><% u.total_points = u.post_activities.sum(:act_points).round(2) %> </p> <%= u.total_points %> <%end%>
any suggestions on how combine these loops or shorten them?
you can refactore code in 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 method) def index @users = user.order("total_points desc") @users.find_each |user| user.update_total_points end end # view <% @users.each |u| %> <%= u.total_points %> <%end%>
Comments
Post a Comment