我正在构建一个简单的排名系统。当评论被投票时,用户的rank
会得到提升。 @comment.rating
会更新并保存。但是,@comment.user.rank
没有。它不报告任何错误,它从不尝试更新或保存它。
这是我的评论控制器中的方法:
def increment
@comment = Comment.find(params[:id])
@comment.rating += 1
@comment.user.rank += User::RANK_VALUES["comment_plus"]
if @comment.save
flash[:notice] = "Voted up"
redirect_to(:back)
else
flash[:notice] = "Error"
redirect_to(:back)
end
end
使用此link_to
:
<%= link_to "+", :controller => "comments", :action => "increment", :id => comment.id %>
这是运行该方法时的日志数据:
Started GET "/comments/increment/12" for 127.0.0.1 at Wed Aug 24 22:35:39 -0400 2011
Processing by CommentsController#increment as HTML
Parameters: {"id"=>"12"}
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = 12 LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 LIMIT 1
AREL (0.2ms) UPDATE "comments" SET "rating" = 9, "updated_at" = '2011-08-25 02:35:39.315081' WHERE "comments"."id" = 12
Redirected to http://localhost:3000/photos/6
有关为什么@ comment.user.rank更新被忽略的任何想法? 注意:我传入的哈希应该没问题;我也试过传递一个直的整数,结果相同。
答案 0 :(得分:2)
也可以尝试拨打@comment.user.save!
。您正在保存评论,但不保存关联的模型。