0

我一直在尝试在不使用 Ajax 重新加载页面的情况下添加评论,在阅读了几个不同的教程之后,这是我到目前为止所想到的,但它不起作用:

在 user_comments/_comments.html.erb 内

    <div id="comment_form">
  <%= simple_form_for [@commentable, @comment], :html => { :multipart => true }, :remote => true do |f| %>
    <div class="picture"><%= image_tag current_user.avatar.url(:thumb) %></div>
    <%= f.input :content, label: false, :placeholder => "Add Comment", :input_html => { :rows => 4 } %>
    <%= f.submit "Add Comment" %>
  <% end %>
   </div>

控制器内部:

def create
@users = User.all
@comment = @commentable.user_comments.new(params[:user_comment])
@comment.user_id = current_user[:id]
#@commentable.user_comments.create(:user_id => current_user[:id])
if @comment.save

  flash[:notice] = "Successfully created comment."
  respond_to do |format|
    format.html { redirect_to @commentable }
    format.js
    #format.js #{ render 'create.js.erb' }
    end
else
  render :new
end
 end

在 create.js.erb 里面

// Display a Javascript alert
<% if remotipart_submitted? %>
    $("#comments_list").append("<%= escape_javascript(render(:partial => 'user_comments/comments')) %>");
<% end %>

我正在使用一个名为:remotipart的宝石

我不知道我在这个过程中缺少什么。在控制台中我得到:

POST http://localhost:3000/assignments/2/user_comments

200 OK
        134ms

这意味着帖子通过,但评论不会被添加回部分。

4

1 回答 1

0

2天后就好了!我修复了它,这是我可以分享并可能会有所帮助的内容:

1-确保将 包含在:remote => true即将提交的表单中 2-检查控制器并查看正在重定向的 Create 操作,在我的情况下,我更改为:

def create
@users = User.all
@comment = @commentable.user_comments.new(params[:user_comment])
@comment.user_id = current_user[:id]
#@commentable.user_comments.create(:user_id => current_user[:id])
if @comment.save
  flash[:notice] = "Successfully created comment."
  respond_to do |format|
    format.html
    format.js   {@comments = @commentable.user_comments}


    end
else
  render :new
end
end

然后确保create.js.erb正确编写:

    $("#comments_list").empty()
$("#comments_list").append("<%= escape_javascript(render(:partial => 'comments')) %>");

给你!我希望有些人为像我这样的新手创建一个合适的教程:)!

于 2013-11-24T00:02:05.930 回答