【发布时间】:2018-09-01 11:40:18
【问题描述】:
每次将消息插入数据库时,我都有一个消息传递系统。它插入重复我得到AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action)。我尝试在 redirect_to 或 self.render 的末尾添加 and return 但没有帮助。它似乎是从创建方法发生的问题
# 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
通过删除
ActionCable.server.broadcast "conversation_#{@conversation.id}", message: render_message(@message)
redirect_to conversation_messages_path(@conversation)
它仍然插入重复的消息
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
这是视图 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>
【问题讨论】:
-
我确实用视图 .html.erb 更新了我的问题,因为我没有任何 javascript @SimpleLime
-
问题已解决 @SimpleLime On Rails 5,rails-ujs 替换 jquery_ujs。如果两者都需要,事件将触发两次。
标签: ruby-on-rails ruby ruby-on-rails-3 rubygems