對於我的應用程序,我有一些項目,用戶可以在其中發表評論(Newcomments類)貼子。現在它發佈很好,但頁面刷新。我正在嘗試使用AJAX/JQUERY,以便它不會刷新頁面。我正在關注這個railscasts教程。Rails - AJAX/JQuery不起作用
所以現在,這些帖子是對我的數據庫和頁面不刷新。但是,當我刷新時,帖子顯示。我爲特定項目呈現我的評論的頁面位於projects/_comments.html.erb上。
問題:我該如何調整它以使它對新評論進行渲染?
newcomments_controller.rb
def create
@newcomment = @commentable.newcomments.new(params[:newcomment])
if @newcomment.save
respond_to do |format|
format.html { redirect_to comments_project_path(@commentable) }
format.js
end
else
render :new
end
end
視圖/ newcomments/_form.html.erb
<span class="comment">
<%= form_for [@commentable, @newcomment], remote: true do |f| %>
<%= f.text_area :content, rows: 3, :class => "span8" %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.submit "Add Comment", :class => "btn btn-header" %>
<% end %>
</span>
視圖/ newcomments/create.js.erb
$('#newcomment').append('<%= j render(@newcomments) %>');
projects_controller.rb
def comments
@commentable = @project
@newcomments = @commentable.newcomments.newest.page(params[:comments_page]).per_page(10)
@newcomment = Newcomment.new
respond_to do |format|
format.html # show.html.erb
format.json { render json: @project.comments }
end
end
項目/ comments.html.erb
<%= render 'comments' %>
項目/ _comments.html.erb
<%= render @newcomments %>
查看/ newcomments/_newcomment.html.erb
<div class="comments">
<%= link_to newcomment.user.name %></strong>
Posted <%= time_ago_in_words(newcomment.created_at) %> ago
<%= newcomment.content %>
</div>
<span class="comment">
<%= form_for [@commentable, @newcomment] do |f| %>
<div class="field">
<%= f.text_area :content, rows: 3, :class => "span8" %>
</div>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="actions">
<%= f.submit "Add Comment", :class => "btn btn-header" %>
</div>
<% end %>
<% unless newcomment.newcomments.empty? %>
<%= render @newcomments %>
<% end %>
</span>