加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 无法在CommentsController中重定向到Nil #troy

发布时间:2020-12-17 02:31:45 所属栏目:百科 来源:网络整理
导读:我想在我的评论控制器中编写我的删除方法.我的评论模型与其他模型有多态关联,但在这种情况下,我们只关注旅行.换句话说,@ trip = @commentable. 注释被删除就好了,但我在CommentsController中不断收到错误ActionController :: ActionControllerError#destroy
我想在我的评论控制器中编写我的删除方法.我的评论模型与其他模型有多态关联,但在这种情况下,我们只关注旅行.换句话说,@ trip = @commentable.

注释被删除就好了,但我在CommentsController中不断收到错误ActionController :: ActionControllerError#destroy:无法重定向到nil!当我redirect_to @commentable这将是评论属于的旅行.

我还在我的创建操作(注释控制器)中重定向到@commentable,并且在用户创建新注释时工作正常.

有小费吗?

view(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

comments_controller.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

解决方法

找出解决方案.将在上面的代码中发布解决方案

def destroy
  @comment = Comment.find(params[:id])
  @commentable = @comment.commentable
  if @comment.destroy
    redirect_to @commentable
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读