私は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
を入力すると、10
は、今では記事の内容を示しており、この記事やテキストエリアにその前のコメントの下に新しいコメントを与えることが、私が作成したコメントをクリックしたときには、このURL http://localhost:3000/comments
に行くと、私はエラー
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
:以下
undefined method `comments' for nil:NilClass
は私のコメントコントローラコードです.erb私はこのエラーを解決する方法を= 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>
を使って記事やフォーラムshow.html.haml
でレンダリングしていますファイルのコードは?私はそれが正しくないと思う。article_id
。新しいコメントを作成するときに、どうすればcommentable_id
とcommentable_type
(記事またはフォーラム)を正しくストロークできますか?これ以外の方法はありますかfind_commentable
?
おかげで、事前
@ commentable.comments.build @またはこのケースであるべきときにエラーがあると思いますあなたの答えにあなたのコードをインデントし、誰かがあなたにそれをするのを待ってはいけません。 – shingara