【发布时间】:2017-11-24 05:44:37
【问题描述】:
我正在使用 Rails 5.0 构建一个事件应用程序,并将 cmets 作为嵌套资源。用户可以创建和销毁 cmets,我正在尝试使用 Ajax/remote: true 实现编辑/更新功能,以便他们可以更新同一页面上的评论,但它不起作用。当我单击编辑链接时,没有任何反应。这是相关代码-
cmets_controller.rb
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
def create
@event = Event.find(params[:event_id])
@comment = @event.comments.create(comment_params)
@comment.user_id = current_user.id
if @comment.save
redirect_to @event
else
render 'new'
end
end
# GET /comments/1/edit
def edit
@event = @comment.event
@comment = @event.comments.find(params[:id])
respond_to do |format|
format.html { render :edit }
format.js {}
end
end
def show
end
def update
if @comment.update(comment_params)
redirect_to @event, notice: "Comment was successfully updated!"
else
render 'edit'
end
respond_to do |f|
format.html { redirect_to @event, notice: "Comment Successfully updated!" }
format.js # render 'comments/update.js.erb'
end
end
def destroy
@event = Event.find(params[:event_id])
@comment = @event.comments.find(params[:id])
@comment.destroy
redirect_to event_path(@event)
end
private
def set_comment
@comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:name, :body)
end
结束
_comment.html.erb
<div class="comment clearfix">
<div class="comment_content">
<div id="comments" class="comment">
<p id="comment_name"><strong><%= @comment.name %></strong></p>
<p id="comment_body"><%= @comment.body %></p>
</div>
<p><%= link_to 'Edit', edit_event_comment_path(comment.event), id: "comments", remote: true %></p>
<p><%= link_to 'Delete', comment.event,
method: :delete,
class: "button",
data: { confirm: 'Are you sure?' } %></p>
</div>
</div>
update.js.erb
$('#comments').append("<%= j render @comment %>");
edit.js.erb
$('#comments').html("<%= j render 'form' %>");
_form.html.erb
<%= simple_form_for([@event, @comment], remote: true) do |f| %>
<%= f.label :comment %><br>
<%= f.text_area :body %><br>
<br>
<%= f.button :submit, label: 'Add Comment', class: "btn btn-primary" %>
<% end %>
在使用 Ajax 之前我从未实现过此操作,所以我可能在这里犯了一些小学生错误。任何帮助表示赞赏。
【问题讨论】:
-
您没有在编辑操作中呈现任何内容...所以什么都没有发生...
-
点击编辑链接时是否有更新评论的表单?
-
@Pavan 要我添加表格吗?
-
你的
edit动作看起来很奇怪,你有一个循环引用:@comment需要设置@event,@event需要设置@comment。@comment.event没有出现任何错误吗? -
@Gerry 没什么,我认为这可能是路由问题,但我不太明白哪里出了问题。
标签: javascript jquery ruby-on-rails ajax