Ruby on Rails:找到未经许可的参数:_method,authenticity_token

时间:2015-10-12 20:45:24

标签: ruby-on-rails parameters

我使用this guide作为从头开始创建消息传递系统的起点。

一切都很好。但出于某种原因,每当我现在尝试通过在我的视图中单击以下链接来创建新对话时

<%= 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

奇怪的是,之前我没有遇到过这个问题,而且我没有做任何改动。问题可能是什么?

1 个答案:

答案 0 :(得分:1)

你的params应该这样定义:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h1>Example</h1>

      <div class="input-group">
        <input type="text" class="form-control"> <span class="input-group-btn input-space">
                    <button class="btn btn-default" type="button">Go!</button>
               </span>

      </div>
    </div>
  </div>
</div>

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