2015-01-11 47 views
0

我的应用程序是在Rails 4.1.1与jQuery。jquery append不工作在Rails ajax视图

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

对于每项活动,用户都可以添加一条新评论 - 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,交替单引号和双引号等等,我很无能。感谢任何指针。

回答

0

我想你已经补充说,打破你选择一个额外的空间:

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

我不知道名字后进行额外的空间将打破选择。接得好 !谢谢。 –