2015-06-13 182 views
0

我试图循环访问我的用户并从关联的post_activites中总结属性act_points,然后将其分配并保存到我的用户表属性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%> 

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

+9

我阅读代码后的第一反应 - 你为什么要在视图中调用save?这是一个巨大的NO-NO。 – BroiSatse

+0

我知道这不是在生产,我再次超新,这是我唯一能想到的原谅我...大声笑 –

回答

3

可以refactore这样的代码:

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

谢谢你,你不知道这有多帮助我了解这个问题,如此多的问题让我感谢 –

+0

@SherwynCooper不客气! – hedgesky