对于我的应用程序,我有一些项目,用户可以在其中发表评论(Newcomments 类)发布。现在它发布得很好,但页面刷新。我正在尝试使用 AJAX/JQUERY,这样它就会在没有页面刷新的情况下发布。我正在关注这个railscasts教程。
因此,现在,帖子已写入我的数据库,并且页面没有刷新。但是当我刷新时,帖子会显示出来。我为特定项目呈现评论的页面位于 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) %>');
项目控制器.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>