我有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_id
和commentable_type
(文章或論壇)?除了這個find_commentable
還有其他方法嗎?
在此先感謝
請在您的答案中縮進您的代碼,不要等待有人向您提供。 – shingara 2012-03-06 08:55:24