announcerreactor
announcerreactor

Reputation: 48

`redirect_to @article` throws the `NoMethodError in Blog::ArticlesController#create` error

I am trying to go through the 'Ruby on Rails Getting Started' tutorial(guides.rubyonrails.org) and I am running into this issue I cannot seem to figure out. I reached the point in the tutorial where I can create an article, but the redirect to see the article immediately after creation does not work and I get an error that says:

NoMethodError in Blog::ArticlesController#create
undefined method `article_url' for #<Blog::ArticlesController:0x00007f814841af20>

Here is my article controller code:

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

and here is my routes.rb (omitted irrelevant code):

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

The only deviation I have done from the tutorial is that I wanted to place the articles in a name space, as well as 1 extra value to enter in the form(category). The only suggestions for fixing my issue when I searched was to make resource into plural but my code already has this and to add @article = Article.new into def new in the controller but this addition made no difference.

I found a work around that will properly redirect after creating a new article that is the line as follows:

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

But this doesn't seem like the "Rails Way"(Convention over Configuration), and I really don't understand why the suggested code in the tutorial is not working for me

Upvotes: 0

Views: 242

Answers (1)

Clara
Clara

Reputation: 2715

The Rails-ey way to redirect to the proper route would be to first check in the terminal with rails routes. There you will see if you want to route to articles#show under the namespace blog that the prefix (first column) is blog_article. You can use this prefix with the _path method like so:

redirect_to blog_article_path(@article)

Upvotes: 1

Related Questions