AbstractController :: DoubleRenderError(此操作多次调用了渲染和/或重定向

时间:2019-05-24 03:49:42

标签: ruby-on-rails ruby actioncable

我创建了一个消息系统,其中一个用户发送消息,另一用户接收实时更新的消息。它以前一直在工作,但是现在我出错了,没有任何渲染或刷新。

AbstractController :: DoubleRenderError(渲染和/或重定向分别是    在此操作中被多次调用。请注意,您只能    调用渲染或重定向,每个动作最多一次。另请注意    既不重定向也不渲染终止操作的执行,所以如果    您要在重定向后退出操作,您需要执行    诸如“ redirect_to(...)然后返回”之类的东西。):

这是messages_controller.rb

class MessagesController < ApplicationController
before_action :authenticate_user!
before_action :set_conversation

def index
   if current_user == @conversation.sender || current_user == 
     @conversation.recipient
     @other = current_user == @conversation.sender ? 
     @conversation.recipient : @conversation.sender
     @messages = @conversation.messages.order("created_at DESC")
   else
   redirect_to conversations_path, alert: "You don't have permission to view this."
   end
   end

def create
  @message = @conversation.messages.new(message_params)
  @messages = @conversation.messages.order("created_at DESC")

 if @message.save
   ActionCable.server.broadcast "conversation_#{@conversation.id}", message: render_message(@message)
   redirect_to conversation_messages_path(@conversation)
 end

end

private

 def render_message(message)
   self.render(partial: 'messages/message', locals: {message: message})
 end

 def set_conversation
   @conversation = Conversation.find(params[:conversation_id])
 end

 def message_params
   params.require(:message).permit(:context, :user_id)
 end
end

我知道错误来自这里

 if @message.save
   ActionCable.server.broadcast "conversation_#{@conversation.id}", message: render_message(@message)
   redirect_to conversation_messages_path(@conversation)
 end

2 个答案:

答案 0 :(得分:0)

在 Message.rb

 after_create_commit { MessageJob.perform_later self }

并创建MessageJob

class MessageJob < ApplicationJob
  queue_as :default

  def perform(message)
   ActionCable.server.broadcast "conversation_#{message.conversation.id}", message: render_message(message)
  end

  private


def render_message(message)
   ApplicationController.renderer.render(partial: 'messages/message', locals: {message: message})
 end

答案 1 :(得分:0)

问题出在Connection.rb 就像这样

module ApplicationCable
class Connection < ActionCable::Connection::Base
   identified_by :current_user

   def connect
   self.current_user = find_verified_user
   logger.add_tags 'ActionCable', current_user.name
   end

   protected
    def find_verified_user
      verified_user = User.find_by(id: cookies.signed['user.id'])
      if verified_user && cookies.signed['user.expires_at'] > Time.now
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

当我更改为它时,

module ApplicationCable
   class Connection < ActionCable::Connection::Base
   end
end