Rails Ajax不重新加载

时间:2015-11-03 03:22:20

标签: javascript jquery ruby-on-rails ajax

创建实时聊天应用,但每当我发布消息时,我都必须重新加载页面以查看我的新消息。聊天本身不会重新加载。

_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

编辑:添加了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 个答案:

没有答案