weixin_33701294 2015-11-03 03:22 采纳率: 0%
浏览 22

Rails Ajax无法重新加载

Creating real time chat app, but whenever I post a message I have to reload the page to see my new message. The chat does not reload by itself.

_form.html.erb

<div class="well">
  <%= form_for @comment, remote: true do |f| %>
    <div class="form-group">
      <%= f.label :body, 'Enter your comment:' %>
      <%= f.text_area :body, rows: 3, class: 'form-control', required: true, maxlength: 2000 %>
      <small class="label label-warning">Cannot be blank or contain more than 2000 symbols.</small>
    </div>

    <%= f.submit 'Post', class: 'btn btn-primary btn-lg' %>
  <% end %>
</div>

_comments.html.erb

<li class="media comment">
  <%= link_to image_tag(comment.user.avatar_url, alt: comment.user.name, class: "media-object"),
              comment.user.profile_url, target: '_blank', class: 'pull-left' %>
  <div class="media-body">
    <h4 class="media-heading"><%= link_to comment.user.name, comment.user.profile_url, target: '_blank' %> says
      <small class="text-muted">[at <%= comment.created_at.strftime('%-d %B %Y, %H:%M:%S') %>]</small></h4>
    <p><%= comment.body %></p>
  </div>
</li>

create.js.erb

publisher = client.publish('/comments', {
  message: '<%= j render @comment %>'
});

publisher.callback(function() {
  $('#comment_body').val('');
  $('#new_comment').find("input[type='submit']").val('Submit').prop('disabled', false)
});

publisher.errback(function() {
  alert('There was an error while posting your comment.');
});

git source

Edit: added comments_controller.rb

class CommentsController < ApplicationController
  def new
    @comment = Comment.new
    @comments = Comment.order('created_at DESC')
  end

  def create
    respond_to do |format|
      if current_user
        @comment = current_user.comments.build(comment_params)
        if @comment.save
          flash.now[:success] = 'Your comment was successfully posted!'
        else
          flash.now[:error] = 'Your comment cannot be saved.'
        end
        format.html {redirect_to root_url}
        format.js
      else
        format.html {redirect_to root_url}
        format.js {render nothing: true}
      end
    end
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
    • ¥15 有赏,i卡绘世画不出
    • ¥15 如何用stata画出文献中常见的安慰剂检验图
    • ¥15 c语言链表结构体数据插入
    • ¥40 使用MATLAB解答线性代数问题
    • ¥15 COCOS的问题COCOS的问题
    • ¥15 FPGA-SRIO初始化失败
    • ¥15 MapReduce实现倒排索引失败
    • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
    • ¥15 找一位技术过硬的游戏pj程序员