find_commentable 为 nil:NilClass 返回未定义的方法"注释"



当我尝试创建新注释(多态关系)时,我的创建方法中不断出现undefined method 'comments' for nil:NilClass。我已经浏览了有关此的其他几个问题,似乎无法找到我的表单/控制器的问题。

这是我的通用部分评论:

<%= form_for [@commentable, Comment.new] do |f| %>
  <%= f.text_area :content %>
  <%= f.submit "Post" %>
<% end %>

请注意,这在我的旅行/节目页面中呈现。窗体呈现良好。如果我更改form_for以[@commentable, @comment]传递参数,则会收到错误undefined method model_name'对于NilClass:Class'

路线.rb

resources :users 
resources :traveldeals
resources :traveldeals do
  resources :comments
end
resources :users do
  resources :comments
end

Railscasts将上述内容写为resources :traveldeals, :has_many => :comments,但我相信这是过时的语法。

comments_controller.rb

class CommentsController < ApplicationController
  before_filter :authenticate, :only => [:create, :destroy]
  def new
    @comment = Comment.new
  end
  def create
    @commentable = find_commentable
    @comment = @commentable.comments.build(params[:comment])
    @comment.user_id = current_user.id
   if @comment.save
      flash[:success] = "Successfully saved comment."  
      redirect_to root_path
    else
      redirect_to current_user
    end
  end
private
  def find_commentable
    params.each do |name, value|
      if name =~ /(.+)_id$/
        return $1.classify.constantize.find(value)
      end
    end
    nil
   end
end

编辑:添加了解决方案,因此上面的代码对我有用。

你的form_for中有@commentable,但是这个变量集在哪里?它似乎没有设置在哪里,我认为这是错误的原因。另请参阅我对你另一个问题的回答。

最新更新