2012-03-06 69 views
0

我有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

回答

0

find_commentable方法,通過_id返回第一個PARAMS後綴。這似乎不適用於你的情況。爲什麼不做簡單的User.find(params[:user_id])?它更簡單,更具可讀性。

+0

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

0

這是一個老問題,但我認爲錯誤是因爲你在做@ commentable.comments.new時,應@ commentable.comments.build 或在這種情況下@ commentable.comments.create