当我想要提升一个"hack“时,我遇到了这个新手错误:
ActionController::ParameterMissing at /hacks/6/upvote
param is missing or the value is empty: vote以请求参数为例:
{"_method"=>"post", "authenticity_token"=>"r+fYieTQDsD6fuonr3oe0YEzkzBXH1S8k6bDENS0wCVr3LEpxGA4mps5saM4RQLvBNDVzsm2zXpGm9TKe3ZIYA==",
"controller"=>"hacks", "action"=>"upvote", "id"=>"6"}我不明白为什么我的@vote没有出现在参数中...
控制器hacks_controller.rb
class HacksController < ApplicationController
skip_before_action :authenticate_user!, only: [:upvote]
def upvote
@vote = Vote.new(vote_params)
@hack = Hack.find(params[:id])
# raise
@vote.hack = @hack
if @vote.save
redirect_to root_path
else
p 'Problème de @vote.save !'
end
end
private
def vote_params
params.require(:vote).permit(:hack_id, :user_id)
end
end模型Vote.rb
class Vote < ApplicationRecord
belongs_to :user
belongs_to :hack
validates :hack, presence: true
end谢谢!
发布于 2018-06-03 21:11:24
Rails强参数是作为批量赋值保护的,不适合这种情况。
要正确创建额外的CRUD方法,您只需将额外的路由添加到资源:
resources :hacks do
post :upvote
delete :downvote
end请注意,我们使用的是POST,而不是GET,因为这是一个非幂等操作。
您也不需要传递任何参数。:hacks_id将出现在path中,您应该从会话中获取当前用户id,而不是请求参数。
通过参数传递用户id是一种非常糟糕的做法,因为仅使用web检查器进行欺骗是非常微不足道的。
class HacksController < ApplicationController
before_action :set_hack!, except: [:new, :index, :create]
# POST /hacks/:hack_id/upvote
def upvote
@vote = @hack.votes.new(user: current_user)
if @vote.save
redirect_to @hack, success: 'Vote created'
else
redirect_to @hack, error: 'Vote could not be created'
end
end
# DELETE /hacks/:hack_id/downvote
def downvote
@vote = @hack.votes.where(user: current_user).first!
@vote.destroy
redirect_to @vote, success: 'Vote deleted'
end
private
# this will raise ActiveRecord::RecordNotFound if
# the id or hack_id param is not valid. This triggers a 404 response
def set_hack!
if params[:id].present?
Hack.find(params[:id])
else
Hack.find(params[:hack_id])
end
end
end然后在你的视图中,你可以像这样创建链接/按钮:
<% if current_user && @hack.votes.where(user: current_user) %>
<%= button_to 'Downvote', hack_downvote_path(@hack), method: :delete %>
<% else %>
<%= button_to 'Upvote', hack_upvote_path(@hack), method: :post %>
<% end %>https://stackoverflow.com/questions/50665925
复制相似问题