2010-09-08 69 views
0

我正在关注为不同模型进行评论的railscasts指南(http://asciicasts.com/episodes/154-polymorphic-association),但我遇到了问题。试图在评论和模型之间使用多态关系

当我尝试到本地主机:3000 /用品/ ID /评论/新,我得到以下错误:

undefined method `comments_path' for #<#<Class:0xb608b40>:0xb607a60> 

它是从我的评论的形式来:

1: <%= form_for([@commentable, @comment]) do |f| %> 
2: <%#= render 'shared/error_messages', :object => f.object %> 
3: <div class="field"> 
4:  <%= f.label :title %><br /> 

这里是评论控制器的新方法的内容:

def new 
    @comment = Comment.new 
    end 

有一点不同于演员,我的routes.db有这样的:

resources :articles do 
    resources :comments 
    end 

的这个代替:

resources :articles, :has_many => :comments 

,如果我不这样做,这样我得到一个路线错误。

任何想法为什么?我知道这个指南是有点老了,我on Rails的3

回答

0

您还没有在这个你的“新”行动分配@commentable变量

它应该像

 
    def new 
    # This may need to change as per the class of the commentable field 
    @commentable = Article.find(params[:article_id'] 
    @comment = Comment.new 
    end 
0

它看起来像Rails不喜欢多态和嵌套路线的组合。我不能保证它会工作,但试试这个:

<%= form_for([@commentable, @comment], :url => new_polymorphic_url([@commentable, @comment])) do |f| %> 

编辑:你缺少一个Rishav提到@commentable初始化,所以尝试,第一。

0

此外,我发现我在每个评论控制器方法中使用“@commentable = find_commentable”。无论如何宣布一次,并允许所有的方法有它吗?