[英]Rails ApplicationController
我正在關注Rails教程( http://tutorials.jumpstartlab.com/projects/blogger.html#blogger-2 ),制作了一個簡單的博客。 在其中一個練習中,它要求我為我的Articles_Controller實現destroy方法(articles是博客文章結構的模型)。
我已經實現了刪除功能,但是此后,當嘗試將redirect_to到article_path(@article)時,它找不到記錄(當然它已被刪除)。 我想知道如何redirect_to到索引頁?
刪除文章后,我得到了rails錯誤頁面,並且:
error: ActiveRecord::RecordNotFound in ArticlesController#show
我的應用程序/控制器/articles_controller.rb:
def destroy
@article = Article.find(params[:id])
flash.notice = "Article '#{@article.title}' destroyed."
redirect_to article_path(@article)
@article.destroy
end
ArticleController#show中定義的方法
def show
@article = Article.find(params[:id])
end
您可以使用redirect_to articles_path
重定向到索引路徑
所以:
def destroy
begin
@article = Article.find(params[:id])
if @article.destroy
redirect_to articles_path, notice: "Article '#{@article.title}' destroyed."
else
redirect_to article_path(@article), alert: "Article could not be destroyed."
end
rescue ActiveRecord::RecordNotFound
redirect_to articles_path, alert: "Article with id '#{params[:id]}' not found"
end
end
如果要重定向到應用程序的索引頁。 你可以做這樣的事情。
def destroy
@article = Article.find(params[:id])
@article.destroy
flash.notice = "Article '#{@article.title}' destroyed"
redirect_to root_index
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.