Ruby on Rails:发现未授权的参数:_method,authenticity_token

7
我以这篇指南作为从零开始创建消息系统的起点。
一切都运行良好。但出现了一个问题,每当我尝试通过点击视图中的以下链接创建新对话时。
<%= link_to 'Message me', conversations_path(sender_id: current_user.id, recipient_id: @user.id), class: 'btn btn-primary', method: :post %>

我遇到了这个错误:
found unpermitted parameters: _method, authenticity_token

以下是参数列表:

{"_method"=>"post", "authenticity_token"=>"BL2XeA6BSjYliU2/rbdZiSnOj1N5/VMRhRIgN8LEXYPyWfxyiBM1SjYPofq7qO4+aqMhgojvnYyDyeLTcerrSQ==", "recipient_id"=>"1", "sender_id"=>"30", "controller"=>"conversations", "action"=>"create"}

我被指示关注于我的控制器中的params.permit行:

class ConversationsController < ApplicationController
  before_action :authenticate_user!

  # GET /conversations
  # GET /conversations.json
  def index
    @users = User.all

    # Restrict to conversations with at least one message and sort by last updated
    @conversations = Conversation.joins(:messages).uniq.order('updated_at DESC')
  end

  # POST /conversations
  # POST /conversations.json
  def create
    if Conversation.between(params[:sender_id], params[:recipient_id]).present?
      @conversation = Conversation.between(params[:sender_id], params[:recipient_id]).first
    else
      @conversation = Conversation.create!(conversation_params)
    end

    redirect_to conversation_messages_path(@conversation)
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def conversation_params
      params.permit(:sender_id, :recipient_id)
    end
end

奇怪的是,我以前没有遇到过这个问题,也没有做任何更改。可能出了什么问题?


啊,我知道了!我在我的development.rb文件中设置了config.action_controller.action_on_unpermitted_parameters = :raise。注释掉这行代码就可以解决问题了。 - anti-destin
1个回答

3
您的参数应该像这样定义:

def conversation_params
  params.require(:conversation).permit(:sender_id, :recipient_id)
end

这应该确保表单自动生成的其他隐藏参数不被阻止。

这解决了问题。感谢快速回复和优秀的答案。添加 require 部分还可以在遇到不允许参数时引发错误。 - anti-destin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接