jquery追加不在Rails ajax视图中工作

时间:2015-01-11 09:42:37

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

我的应用程序使用jquery在Rails 4.1.1上。

该页面显示活动列表,每个活动都包含在部分活动中。

对于每个活动,用户可以添加新评论 - link_to新评论方法的ID动态地基于活动ID,即#newcomment_185。

对于每个活动,评论显示在列表中--- ul的id动态地基于活动ID,即#commentslist_185。

_activity.html.erb (my activity partial)
<p>The activity content is here.
<%= link_to t('new_comment'), new_activity_comment_path(activity_id: activity.id), :id => "newcomment_#{activity.id}", remote: true, :class => "button tiny " %></p>
<ul id="commentslist_<%= activity.id %> "> Comments: <%= activity.comments.count %>
 <% activity.comments.each do |comment| %>
    <li> <%= comment.body %> (par <%= comment.commenter.name %>) </li> 
<% end %>
</ul>

comments_controller.erb
class CommentsController < ApplicationController
load_and_authorize_resource

  def new
    @comment = Comment.new commenter: current_user, activity_id: params[:activity_id]
    respond_to do |format|
      if request.xhr?
        format.js
        format.html { render layout: false }
      else
        format.js { render :action => 'new' }
        format.html { render 'new' }
        format.json { render json: @comment }
      end
    end
  end

  def create
    @comment = Comment.new(comment_params)
    @comment.commenter = current_user
    respond_to do |format|
      if @comment.save
        format.js
        format.html { redirect_to root_path, notice: 'Commentaire ajouté' }
      else
        format.js { render 'update' }
        format.html { render 'new' }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def comment_params
    params.require(:comment).permit(:body, :activity_id, :commenter_id)
  end
end

/app/views/comments/new.js.erb
$('#newcomment_<%= @comment.activity_id.to_s %>').hide().after('<%= j render("form") %>');
$('#commentform').slideDown(350);

/app/views/comments/create.js.erb
$('#commentform_<%= @comment.activity_id.to_s %>').remove();
$('#newcomment_<%= @comment.activity_id.to_s %>').show();
$('#commentslist_<%= @comment.activity_id.to_s %> ul').append('<%= j render(@comment) %>');

问题在于最后一行---一切正常但是这个。 li元素未添加到ul。

在Chrome控制台预览中,已解析的js似乎没问题:

$('#commentform_188').remove();
$('#newcomment_188').show();
$('#commentslist_188 ul').append('<li> test 1 (by John Doe) <\/li>');

任何地方都没有错误消息。我尝试了最后一行的不同版本---没有ul,交替单引号和双引号等等。我无能为力。谢谢你的任何指示。

1 个答案:

答案 0 :(得分:0)

我认为你添加了一个额外的空间来破坏你的选择器:

<="commentslist_<%= activity.id %> ">
<="commentslist_<%= activity.id %>">