我的 Rails 3 应用程序中有以下代码:
def like
@suggestion = Suggestion.find(params[:id])
Suggestion.update_all("votes = (votes + 1)")
redirect_to suggestions_url
end
def dislike
@suggestion = Suggestion.find(params[:id])
Suggestion.update_all("votes = (votes - 1)")
redirect_to suggestions_url
end
它正在工作,但不是更新当前建议,而是全部更新。所以我把它改成:
def like
@suggestion = Suggestion.find(params[:id])
@suggestion.update_all("votes = (votes + 1)")
redirect_to suggestions_url
end
def dislike
@suggestion = Suggestion.find(params[:id])
@suggestion.update_all("votes = (votes - 1)")
redirect_to suggestions_url
end
但后来我得到:
undefined method `update_all' for #<Suggestion:0x007f87c2b918a0>
所以然后我尝试@suggestion.update_attribute(:votes, '1')
了但是将值重置为1而不是增加它。
实现这一目标的正确方法是什么?我只希望当前建议的整数(票数)在每次保存时增加/减少 1。
我也试过以下没有运气:
def like
@suggestion = Suggestion.find(params[:id])
@suggestion.increment(:votes)
redirect_to suggestions_url
end