find_commentable为nil返回undefined方法`comments':NilClass

时间:2012-04-11 23:36:54

标签: ruby-on-rails ruby-on-rails-3

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

以下是我评论的通用部分:

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

请注意,这是在我的traveldeal / show页面中呈现的。表格很好。如果我将form_for更改为传递参数[@commentable, @comment],我会收到NilClass的错误undefined method model_name':Class`

的routes.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

编辑:添加了解决方案,以便上面的代码适合我。

1 个答案:

答案 0 :(得分:1)

@commentable中有form_for,但该变量集在哪里?它似乎没有设置,我认为这是错误的原因。另请参阅my answeryour other question