I have a messaging system every time I insert a message into the database. it insert duplicates im getting AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action)
. I tried to add and return
at the end of redirect_to or self.render
but it did not help. the problem it seems to be happening from the create method
# app/controllers/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
This is an image from my terminal
by removing
ActionCable.server.broadcast "conversation_#{@conversation.id}", message: render_message(@message)
redirect_to conversation_messages_path(@conversation)
it still insert duplicates messages
def create
@message = @conversation.messages.new(message_params)
@messages = @conversation.messages.order("created_at DESC")
@message.save
end
this image of terminal before removing from the code
This an image from database show that it inserting duplicates
This new image from the terminal after i inserted
this is the view app/views/messages/index.html.erb
<div class="row">
<div class="col-md-3 text-center">
<%= image_tag avatar_url(@other), class: "img-circle avatar-medium" %>
<strong><%= @other.fullname %></strong>
<%= link_to "View Profile", @other, class: "btn btn-default" %>
</div>
<div class="col-md-9">
<div class="panel panel-default">
<div class="panel-heading">
Conversation with <%= @other.fullname %>
<input id="conversation_id" type="hidden" value="<%=
@conversation.id %>">
</div>
<div class="panel-body">
<div class="container text-center">
<%= form_for [@conversation, @conversation.messages.new], remote: true do |f| %>
<div class="form-group">
<%= f.text_field :context, placeholder: "Add a personal message", class: "form-control" %>
</div>
<%= f.hidden_field :user_id, value: current_user.id %>
<div>
<%= f.submit "Send Message", class: "btn btn-normal" %>
</div>
<% end %>
</div>
</div>
</div>
<div id="chat">
<%= render @messages %>
</div>
Aucun commentaire:
Enregistrer un commentaire