I would like to set an element content in case it is empty.
The html.erb code is below:
<div class="comments-section">
<% if micropost.comments.any? %>
<ol id="comments_micropost-<%= micropost.id %>">
<% micropost.comments.each do |comment| %>
<%= render comment %>
<% end %>
</ol>
<% end %>
</div>
The element I want to set the content is <div class="comments-section">. Its content is empty when the micropost has not yet comments.
I handle the create action of comments with javascript in create.js.erb: I wrote two lines of code, depending on whether micropost.comments is nil or it is not nil:
Case 1: micropost has not yet comments (micropost.comments.any? is false):
$('#micropost-<%= @micropost.id %>').find('.comments-section').html("<%= escape_javascript(render partial: 'comments/first_comment') %>");
Case 2: micropost has already comments (micropost.comments.any? is true):
var comments = $('ol#comments_micropost-<%= @micropost.id %>');
comments.append('<%= escape_javascript(render partial: @comment) %>');
Both pieces of code work when are used separately. However the code of case 1 do not work when inserted together with case 2 in the following conditional:
if (comments == null) {
$('#micropost-<%= @micropost.id %>').find('.comments-section').html("<%= escape_javascript(render partial: 'comments/comments') %>");
}
else {
comments.append('<%= escape_javascript(render partial: @comment) %>');
};
I do not understand why when if (comments == null) the code is not executed. I also tried with if (comments == undefined) and with if (!comments) with no improvements.
Instead, the else part of the conditional is successfully executed.
Aucun commentaire:
Enregistrer un commentaire