Reputation: 936
Im create a messages system where one user send message and the other user receive the message with realtime update. It was working before but now im getting in error and nothing render or get refreshed.
AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".):
here is 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
I know the error is coming from here
if @message.save
ActionCable.server.broadcast "conversation_#{@conversation.id}", message: render_message(@message)
redirect_to conversation_messages_path(@conversation)
end
Upvotes: 1
Views: 402
Reputation: 936
the issue was with Connection.rb It was like this
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
and when i changed to this it worked
module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
Upvotes: 0
Reputation: 1596
In Message.rb
after_create_commit { MessageJob.perform_later self }
and create 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
Upvotes: 0