2015-01-11 51 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

我不知道名字後進行額外的空間將打破選擇。接得好 !謝謝。 –