コメントコントローラーにdeleteメソッドを書き込もうとしています。私のコメントモデルには他のモデルとのポリモーフィックな関連性がありますが、この場合は旅行に焦点を当てます。言い換えれば、@ trip=@commentableです。
ActionController::ActionControllerError in CommentsController#destroy: Cannot redirect to nil!
コメントは問題なく削除されますが、コメントが属していたトリップである@commentableにredirect_toすると、エラーが発生し続けます。
また、作成アクション(コメントコントローラー)で@commentableにリダイレクトしました。これは、ユーザーが新しいコメントを作成するときに問題なく機能します。
任意のヒント?
ビュー(trips / show.html.erb)
<% if !@commentable.comments.empty? %>
<% @commentable.comments.each do |comment| %>
<!-- Content -->
<%= link_to comment, :method => :delete do %> delete <% end %>
<% end %>
<% end %>
アクションの作成に役立つコメントフォーム
<%= form_for [@commentable, Comment.new] do |f| %>
<%= f.text_area :content %>
<div id="comment_submit_button"><%= f.submit "Comment" %></div>
<% end %>
trips_controller.rb
def show
@trip = @commentable = Trip.find(params[:id])
@comments = Comment.all
end
コメント_controller.rb
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
@comment.user_id = current_user.id
if @comment.save
redirect_to @commentable
end
end
def destroy
# @commentable = find_commentable this line was wrong
@comment = Comment.find(params[:id])
@commentable = @comment.commentable #this line fixed it
if @comment.destroy
redirect_to @commentable
end
end
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end