我正在尝试在我的评论控制器中编写我的删除方法。我的评论模型与其他模型具有多态关联,但在这种情况下,我们将只关注旅行。换句话说,@trip = @commentable。
评论被删除得很好,但是ActionController::ActionControllerError in CommentsController#destroy: Cannot redirect to nil!
当我重定向到 @commentable 时,我不断收到错误消息,这将是评论所属的旅程。
我还在我的创建操作(评论控制器)中重定向到@commentable,当用户创建新评论时它工作得很好。
有小费吗?
查看 (trips/show.html.erb)
<% if !@commentable.comments.empty? %>
<% @commentable.comments.each do |comment| %>
<!-- Content -->
<%= link_to comment, :method => :delete do %> delete <% end %>
<% end %>
<% end %>
适用于创建操作的评论表单
<%= form_for [@commentable, Comment.new] do |f| %>
<%= f.text_area :content %>
<div id="comment_submit_button"><%= f.submit "Comment" %></div>
<% end %>
trips_controller.rb
def show
@trip = @commentable = Trip.find(params[:id])
@comments = Comment.all
end
评论控制器.rb
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
@comment.user_id = current_user.id
if @comment.save
redirect_to @commentable
end
end
def destroy
# @commentable = find_commentable this line was wrong
@comment = Comment.find(params[:id])
@commentable = @comment.commentable #this line fixed it
if @comment.destroy
redirect_to @commentable
end
end
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end