目前,我的應用程序能夠向已有評論的微博追加評論。下面是_micropost.html.erb
(簡體):如何使用Ajax在創建後立即顯示第一條評論和僅有一條評論
<li id="micropost-<%= micropost.id %>">
<span class="content">
<%= micropost.content %>
</span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
~ <%= link_to "Comment", "#", class: "comment-link", remote: true %>
<% if micropost.comments.any? %>
~ <%= link_to "Show/hide comments", "#", class: "comments-link", remote: true %>
<% end %>
</span>
<% if logged_in? && (current_user == micropost.user || current_user.friend?(micropost.user)) %>
<div class="comment-section">
<%= form_for(current_user.comments.build, remote: true) do |f| %>
<%= f.hidden_field :micropost_id, value: micropost.id %>
<%= f.text_area :content, rows: "1", class: "comment_area" %>
<%= f.submit "Comment", class: "btn btn-primary btn-sm" %>
<% end %>
</div>
<% end %>
<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>
</li>
create.js.erb
是:
var comments = $('ol#comments_micropost-<%= @micropost.id %>');
comments.append('<%= escape_javascript(render partial: @comment) %>');
因爲它是設想,create.js.erb
意味着創建添加到其他意見的評論,那就是創建的評論是不第一。在這種情況下,var comments
不爲空,最後一行代碼將註釋附加到其他註釋的列表中。
此外,如果micropost.comments不爲零,用戶可以使用「顯示/隱藏評論」鏈接,切換與id="comments_micropost-<%= micropost.id %>"
順序列表具有這種配置的問題是,如果將用戶添加到任何微博第一條評論(這是用戶在micropost.comments == 0
時寫下他的評論),如果沒有刷新頁面,就沒有機會看到結果。
所以我問:我該如何編輯create.js.erb
,以便用戶可以立即看到發佈第一條評論的結果,並將「顯示/隱藏評論」鏈接添加到頁面中?
我試着下面的代碼,但它不工作:
if (comments !== null) {
comments.append('<%= escape_javascript(render partial: @comment) %>');
} else {
$('#micropost-<%= @micropost.id %>').find('.comments-section').append("<ol id='comments_micropost-<%= @micropost.id %>'><%= escape_javascript(render partial: @comment) %></ol>");
$('#micropost-<%= @micropost.id %>').find('.timestamp').append(" ~ <%= link_to 'Show/hide comments', '#', class: 'comments-link', remote: true %>");
};