【发布时间】:2018-05-05 01:27:03
【问题描述】:
我正在尝试创建一个带有 2 个操作按钮的基本应用:一个用于添加正分,一个用于添加负分。但是,当我尝试添加负分时,它会添加正分。我的代码如下所示。
控制器:
def profile
@user = User.find(params[:id])
@record = Record.where(user_id: @user.id)
@recordid = Record.find_by(user_id: @user.id)
end
def add_positive
@user = User.find(params[:id])
@recordid = Record.find_by(user_id: @user.id)
@recordid.positivescore +=1
if @recordid.save
redirect_back(fallback_location: records_path)
end
end
def add_negative
@user = User.find(params[:id])
@recordid = Record.find_by(user_id: @user.id)
@recordid.negativescore +=1
if @recordid.save
redirect_back(fallback_location: records_path)
end
end
我的看法:
<%= @record.each do |user_record| %>
Positive: <%= user_record.positivescore %> <%= button_to "Add Positive Score", :action => "add_positive" %>
Negative: <%= user_record.negativescore %> <%= button_to "Add Negative Score", :action => "add_negative" %>
<% end %>
我面临的问题 - 每当我尝试添加负分时,它反而会增加正分。在我的头撞墙几个小时后,我发现这是因为我的 routes.rb 文件而发生的。
Routes.rb:
post '/profile/:id', to: 'users#add_positive'
post '/profile/:id', to: 'users#add_negative'
这让我意识到我可能错误地处理了整个问题,我不应该在我的控制器中定义 3 个单独的方法。有人可以指出我应该如何应该这样做吗?
【问题讨论】:
-
您可以将您的路线更改为
post '/profile/:id/add_positive', to: 'users#add_positive',对于否定也是如此。无论如何,似乎用户有很多记录,但你只得到一个记录ID(带有find_by)。这将更新来自用户的一条随机记录。你应该通过record_id -
所以我想我是在正确的轨道上。非常感谢@Pablo,那行得通!想要留下答案以便我接受?
标签: ruby-on-rails model-view-controller