铁轨上的干红宝石

时间:2015-06-13 09:13:44

标签: ruby-on-rails ruby

我正在尝试遍历我的用户并从关联的act_points中对属性post_activites求和,然后将其分配并保存到我的用户表属性total_points。下面的代码对我有用,但它不遵循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%>

有关如何组合这些循环或缩短它们的任何建议吗?

1 个答案:

答案 0 :(得分:3)

您可以通过以下方式重构代码:

# 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%>