【问题标题】:Do I need to reload the comment object or the partial that contains the comment in case of using Ajax in Rails 3?如果在 Rails 3 中使用 Ajax,是否需要重新加载评论对象或包含评论的部分?
【发布时间】:2013-11-22 18:15:13
【问题描述】:

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

在 user_cmets/_cmets.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

的 Gem

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

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

200 OK
        134ms

这意味着帖子通过了,但评论没有被添加回部分。

【问题讨论】:

    标签: ruby-on-rails-3 jquery comments remotipart


    【解决方案1】:

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

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

    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')) %>");
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      相关资源
      最近更新 更多