没有嵌套路线的多态关联事件

问题描述:

我有2个模型文章和论坛,它们与评论模型有多态关联。没有嵌套路线的多态关联事件

我正在使用简单的路由如下。

的routes.rb

resources :articles 
resources :comments 
resources :forums 

以下是我为文章和论坛机型代码:在评论

has_many :comments, :as => :commentable,:dependent => :destroy 

模式

belongs_to :commentable, :polymorphic => true 

现在,当我进入http://localhost:3000/articles/10

它显示了文章的内容和下面这篇文章,一个文本赋予新的评论,但是当我点击创建注释它进入这个网址http://localhost:3000/comments,我得到以下错误

在以前的评论
undefined method `comments' for nil:NilClass 

以下是我评论控制器代码

def create 
    @commentable = find_commentable 
    @comment = @commentable.comments.new(params[:comment]) 

    if @comment.save 
    flash[:notice] = "Successfully saved comment." 
    redirect_to(articles_url, :notice => 'Articlecmnt was successfully created.') 
    else 
    render :action => 'new' 
    end 
end 

def new 
    @comment = Comment.new 
end 

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

以下是我的index.html .erb我在文章和论坛show.html.haml正在呈现文件代码中使用= render :template=>"comments/index"

<% form_for [@commentable, Comment.new] do |form| %> 

    <table> 
    <tr> 
     <td><%= form.text_area :commentcontent, :rows => 5 %></td> 
     <td><%= form.hidden_field :user_id, :value => @current_user.id %></td> 
    </tr> 
    <tr><td><%= submit_tag "Add comment" %></td></tr> 
    </table> 

<% end %> 

<ul id="comments"> 
    <% @comments.each do |comment| %> 
    <li> 
    <p> 
     <b>Posted <%= time_ago_in_words(comment.created_at) %> ago</b> 
    </p> 
    <%= comment.commentcontent %><b> by <%= @current_user.email %></b> 
    </li> 

    <% end %> 
</ul> 

如何解决这个问题?我认为它没有得到正确的article_id。在创建新评论时,我如何纠正commentable_idcommentable_type(文章或论坛)?除了这个find_commentable还有其他方法吗?

在此先感谢

+0

请在您的答案中缩进您的代码,不要等待有人向您提供。 – shingara 2012-03-06 08:55:24

find_commentable方法,通过_id返回第一个PARAMS后缀。这似乎不适用于你的情况。为什么不做简单的User.find(params[:user_id])?它更简单,更具可读性。

+0

谢谢,但没有它不工作shingara ... – Nikita 2012-03-06 09:35:43

这是一个老问题,但我认为错误是因为你在做@ commentable.comments.new时,应@ commentable.comments.build 或在这种情况下@ commentable.comments.create