Rails 3 - "未定义的方法' comments_path'使用可注释的多态关联构建评论的共享表单时出错

时间:2011-08-17 18:17:58

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

我在构建评论表单时遇到问题,我正在通过“可评论”使用多态关系。我现在能够显示评论(如果我播种的话),所以我觉得我非常接近。评论表格也会显示,但是当我提交时,它会失败。

我被发送到“/ comments”,我收到以下错误:

NoMethodError in CommentsController#create 

undefined method `comments' for nil:NilClass

Application Trace
app/controllers/comments_controller.rb:5:in `create' (  @comment = @commentable.comments.build(params[:comment]) )

**首先,为什么要把我送到'/ comments'?这似乎不对。

以下是相关代码,如果您需要更多,请与我们联系。

模型:

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true

  default_scope :order => 'comments.created_at DESC'
end

class Track < ActiveRecord::Base

  has_many :comments, :as => :commentable 
  ...
end

view(comments / form) - 然后在Track#show中显示为部分

<% form_for [@commentable, @comment] do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_area :name %>
  </p>

  <p>
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </p>

  <p><%= f.submit "Submit" %></p>
<% end %>

评论控制员:

def create  
  @commentable = find_commentable  
  @comment = @commentable.comments.build(params[:comment])  
  if @comment.save  
    flash[:notice] = "Successfully saved comment."  
    redirect_to :id => nil  
  else  
    render :action => 'new'  
  end  
end

def new
  @comment = Comment.new
end

private

def find_commentable  
  params.each do |name, value|  
    if name =~ /(.+)_id$/  
      return $1.classify.constantize.find(value)  
    end  
  end  
  nil  
end

路线:

resources :tracks, :has_many => :comments
resources :comments

这是我的第一篇文章,所以让我知道我是否可以改进这个问题!非常感谢。

1 个答案:

答案 0 :(得分:0)

我在这段代码中没有看到任何错误。我想,您忘记在某处设置@track@commentable变量,您可以在其中调用评论。

尝试检查应用程序错误跟踪以查看发生的位置。