ruby-on-rails - 无法在 CommentsController#destroy 中重定向到 Nil(多态关联)

标签 ruby-on-rails ruby-on-rails-3 associations polymorphic-associations

我正在尝试在我的评论 Controller 中编写我的删除方法。我的评论模型与其他模型具有多态关联,但在这种情况下,我们将只关注旅行。换句话说,@trip = @commentable。

评论被删除就好了,但我一直收到错误 ActionController::ActionControllerError in CommentsController#destroy: Cannot redirect to nil!当我重定向到 @commentable 时,这将是评论所属的旅程。

我还在我的创建操作(评论 Controller )中重定向到 @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

评论 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

关于ruby-on-rails - 无法在 CommentsController#destroy 中重定向到 Nil(多态关联),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10158133/

相关文章:

cakephp - 如何按条件过滤关联模型?

ruby-on-rails - Rails 迁移 : t. 引用具有替代名称?

php - 在 CakePHP 3.x 中保存 HasMany 关联数据

ruby-on-rails - Shoulda on Rails - 应该推迟 render_with_layout

ruby-on-rails - 需要在 rails outlet 中正确获取主要的 Ember outlet

ruby-on-rails - 在一个声明中使用 ActiveRecord 序列化多个属性?

ruby-on-rails - Rails 3 ActiveRecord 查询 : find the number of this product that have been ordered by this user

ruby - 测试 ruby​​ gem 二进制文件

ruby-on-rails - 在 before_update 中更新模型

ruby-on-rails-3 - Rails 3 太阳黑子限制选定记录