当我点击链接时,我试图增加模型中列的值,并且我继续在属性上得到未定义的方法错误,我不知道我做错了什么
模型
class VisitorsController < ApplicationController
def inc_adviser
self.adviser = self.adviser + 1
self.save
redirect_to root_path
end
end
路线
match '/adviser' => 'visitors#inc_adviser'
查看
<%= link_to 'Adviser', '/adviser', method: :post %>
有人能说出问题是什么吗?
由于
答案 0 :(得分:0)
self
是控制器实例,而不是您期望它的模型实例。你需要从某个地方获取一个模型实例并在其上增加计数器:
def inc_adviser
# Something like this, don't have enough information to be more specific.
model = WhateverModel.find(params[:id])
model.adviser = model.adviser + 1
model.save
redirect_to root_path
end
当然,这取决于竞争条件,因此您应该使用increment_counter
代替:
def inc_adviser
WhateverModel.increment_counter(:adviser, params[:id])
redirect_to root_path
end