用javascript重新加载div - Rails

时间:2016-07-31 02:27:02

标签: javascript jquery ruby-on-rails ruby ajax

我正在创建聊天,但我想在不重新加载页面的情况下显示消息。 我的数据库正在保存消息,但我需要重新加载页面才能显示它们。

我的索引:

<div class="panel panel-default">
            <div class="panel-heading">
                Conversa com <%= @other.fullname %>
            </div>
            <div class="panel-body">
                <div class="container">

                    <%= form_for [@conversation, @conversation.messages.new], remote: true do |f| %>
                        <div class="form-group">
                            <%= f.text_area :content, placeholder: "Escreva a mensagem", class: "form-control" %>
                        </div>
                        <%= f.hidden_field :user_id, value: current_user.id %>

                        <div class="actions">
                            <%= f.submit "Enviar mensagem", class: "btn btn-primary" %>
                        </div>
                    <% end %>

                </div>
            </div>
        </div>

        <div id="chat">
            <%= render @messages, locals: {conversation: @conversation} %>
        </div>

    </div>

_messages.html.erb

<div class="panel" id="refresh">
    <div class="panel-body">
        <%= image_tag message.user.avatar.url, class: "img-circle avatar-small" %>
        <strong><%= message.user.fullname %></strong>

        <span class="pull-right"><%= message.message_time %></span>
        <br>
        <div class="row-space-2">
            <%= message.content %>
        </div>
    </div>
</div>

消息控制器

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: "Você não tem permissão para acessar essa página."
        end
    end

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

        if @message.save
            respond_to do |format|
                format.js
            end
        end
    end

    private

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

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

model message.rb

class Message < ApplicationRecord
  belongs_to :conversation
  belongs_to :user

  validates_presence_of :content, :conversation_id, :user_id

  def message_time
    created_at.strftime("%v")
  end
end

如何每1秒重新加载div刷新(_messages.html.erb),以显示聊天的新消息。

我正在学习RoR,所以如果我没有说清楚我想做什么,我很抱歉。

ps:由于一些原因,我无法使用WebSockets。

0 个答案:

没有答案