参数缺失或值为空:会话

param is missing or the value is empty: conversation

这是这个话题的后续:

我有以下行:<%= button_to 'Message me', conversations_path(sender_id: current_user.id, recipient_id: @user.id), class: 'btn btn-primary m-t' %>

但是当我点击按钮时,出现错误:param is missing or the value is empty: conversation

我可以看到 conversation 不在参数散列中:{"authenticity_token"=>"r5pwStXl6NwEgqqq0GT0RQxCqsGHrTVsh4Q7HviX+re5k+XOs2ioRv9kZqvDGz9Ch/6O6D1nOMjscquHQJlB+g==", "recipient_id"=>"1", "sender_id"=>"2", "controller"=>"conversations", "action"=>"create"}

正如另一个线程中所建议的那样,将 require(:conversation) 添加到控制器很有帮助:

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.require(:conversation).permit(:sender_id, :recipient_id)
    end
end

这工作了一段时间,但由于某种原因停止工作了。我应该如何解决这个问题?为什么它停止工作了?

手动添加 'conversation' 到散列似乎有效:<%= button_to 'Message me', conversations_path(conversation: { sender_id: current_user.id, recipient_id: @user.id }), class: 'btn btn-primary m-t' %>.

我还必须修复控制器以考虑嵌套:

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

  redirect_to conversation_messages_path(@conversation)
end