首页 > 解决方案 > `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.newdef new控制器中,但这个添加没有任何区别。

我找到了一种解决方法,可以在创建新文章后正确重定向,如下所示:

redirect_to :action => "show", :id => @article.id

但这似乎不像“Rails Way”(Convention over Configuration),我真的不明白为什么教程中建议的代码对我不起作用

标签: ruby-on-railsruby

解决方案


Rails-ey 重定向到正确路线的方法是首先使用rails routes. 在那里,您将看到是否要路由到前缀(第一列)为articles#show的命名空间下。您可以将此前缀与如下方法一起使用:blogblog_article_path

redirect_to blog_article_path(@article)

推荐阅读