ruby-on-rails - `redirect_to @article` 在 Blog::ArticlesController#create 中抛出 `NoMethodError` 错误
问题描述
我正在尝试阅读“Ruby on Rails 入门”教程(guides.rubyonrails.org),但我遇到了这个问题,我似乎无法弄清楚。我在教程中达到了可以创建文章的位置,但是在创建后立即查看文章的重定向不起作用,并且我收到一条错误消息:
NoMethodError in Blog::ArticlesController#create
undefined method `article_url' for #<Blog::ArticlesController:0x00007f814841af20>
这是我的文章控制器代码:
class Blog::ArticlesController < ApplicationController
def new
@article = Article.new
end
def create
@article = Article.new(params.require(:article).permit(:title, :category, :text))
@article.save
redirect_to @article # <-- This line throws error
end
def show
@article = Article.find(params[:id])
end
end
这是我的 routes.rb (省略不相关的代码):
Rails.application.routes.draw do
# <-- other get functions here
get 'blog', to: 'blog#index'
namespace :blog do
resources :articles # <-- Suggestions were to make these plural
end
root 'about#index'
end
我与教程的唯一偏差是我想将文章放在名称空间中,以及在表单(类别)中输入的 1 个额外值。当我搜索时解决我的问题的唯一建议是制作resource
复数,但我的代码已经有了这个并添加@article = Article.new
到def new
控制器中,但这个添加没有任何区别。
我找到了一种解决方法,可以在创建新文章后正确重定向,如下所示:
redirect_to :action => "show", :id => @article.id
但这似乎不像“Rails Way”(Convention over Configuration),我真的不明白为什么教程中建议的代码对我不起作用
解决方案
Rails-ey 重定向到正确路线的方法是首先使用rails routes
. 在那里,您将看到是否要路由到前缀(第一列)为articles#show
的命名空间下。您可以将此前缀与如下方法一起使用:blog
blog_article
_path
redirect_to blog_article_path(@article)
推荐阅读
- bash - 这个单行脚本的哪一部分是特定于 zsh 的?
- c# - C# 锯齿状数组到列表列表
- ios - 如何在 SwiftUI 中使用 PencilKit 绘制图像?
- go - 无法使用 protoc-gen-go-grpc 正确生成代码
- oracle - 使用 Oracel PL/SQL 将制表符分隔的文本转换为 XMLType
- laravel - 运行命令 npm run dev 时如何解决错误
- mysql - MySQL - 更新 PDO 中没有 id 的行
- excel - Access 中的 VBA 代码用于从查询导出中创建具有多个条件格式规则的 Excel 文件
- python - discord.py 中的客户端和 Cogs
- android - 如何在没有 NFC 的情况下在 Android 中实现蓝牙 OOB 配对?