2017-04-09 114 views
1

是的,我已經檢查過here。它沒有工作。部分渲染集合一次太多

的Rails: 5.0.2 紅寶石: 2.4.0

我有意見,每次調用時間集合,它呈現一個時間太多和一個空的評論總是出現低於別人當沒有評論時,一個空的仍然呈現。

下面是代碼:

查看

<h2>Add a comment:</h2> 
<%= render 'comments/form' %> 

<h2>Comments</h2> 
<%= render @video.comments || "There are no comments yet." %> 

表局部

<%= form_for([@video, @video.comments.new]) do |f| %> 
    <p> 
     <%= f.label :name %><br> 
     <%= f.text_field :commenter %> 
    </p> 
    <p> 
     <%= f.label :body %><br> 
     <%= f.text_area :body %> 
    </p> 
    <p> 
     <%= f.submit %> 
    </p> 
<% end %> 

評論部分

<p> 
    <strong>Name:</strong> 
    <%= comment.commenter %> 
</p> 

<p> 
    <strong>Comment:</strong> 
    <%= comment.body %> 
</p> 

<p> 
    <%= link_to 'Destroy Comment', [comment.video, comment], 
       method: :delete, 
       data: { confirm: 'Are you sure?' } %> 
</p> 

控制器

def create 
    @video = Video.find(params[:video_id]) 
    @comment = @video.comments.create(comment_params) 
    redirect_to video_path(@video) 
end 

def destroy 
    @video = Video.find(params[:video_id]) 
    @comment = @video.comments.find(params[:id]) 
    @comment.destroy 
    redirect_to video_path(@video) 
end 

private 
def comment_params 
    params.require(:comment).permit(:commenter, :body) 
end 

有誰知道爲什麼會呈現局部的多餘的時間?

回答

1

您可以嘗試致電.scope在評論協會:

<%= render @video.comments.scope || "There are no comments yet." %> 
+0

這實際上並努力消除空的評論,但是現在當沒有意見仍然不輸出「有沒有評論。 「我可以創建一個JavaScript函數來提供這種功能,但我不希望這樣做。 –

+0

好吧,有可能通過使用'if-else'條件來渲染評論而不使用javascript來實現這一點:<%if @ video.comments.scope.any? %>等... –