我正在使用Rails 5.0构建一个事件应用程序,并将注释作为嵌套资源。用户可以创建和销毁评论,我试图使用Ajax / remote实现编辑/更新功能:true,这样他们就可以在同一页面上更新评论,但它不起作用。当我点击编辑链接时没有任何反应。这是相关代码 -
comments_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之前从未实现过此操作,所以我可能会在这里犯一些小学生错误。任何帮助表示赞赏。
答案 0 :(得分:0)
您正在使用此
调用控制器上的编辑方法<%= link_to 'Edit', [comment.event, comment], id: "comment", remote: true %>
你没有 edit.js.erb
要更新您的评论,您必须创建一个表单,其中的操作URL指向您的更新方法,并将其标记为远程true。然后当你提交时,它会直接达到更新,不需要通过编辑方法。
有一种创建带有ajax选项的表单的方法,默认名为form_with,你可以在这里查看它的指南和文档:
http://guides.rubyonrails.org/working_with_javascript_in_rails.html#form-with
更新问题后更新答案
你的表格需要成为这样的
<%= simple_form_for :comment, :url => "/events/#{comment.event_id}/comments/#{comment.id}", :method => :put do |f| %>
<%= f.label :comment %><br>
<%= f.text_area :body %><br>
<br>
<%= f.button :submit, label: 'Add Comment', class: "btn btn-primary" %>
<% end %>