Error adding articles on the page

49 views Asked by At

Following the example guides.rubyonrails.org/getting_started.html I receive an error undefined method `articles' for nil:NilClass in attempt of addition of article on the page.

routes.rb

Rails.application.routes.draw do
  root :to => redirect('/pages/1')
  resources :articles
  resources :pages do
    resources :articles
  end

views/articles/new.html.erb

<h1>New Article</h1>
<%= form_for([@page, @page.articles.build]) do |f| %>
  <p>
    <%= f.label :item %><br>
    <%= f.text_field :item %>
  </p>
  <p>
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>

articles_controller.rb

class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @page = Page.find(params[:page_id])
    @article = @page.articles.create(article_params)
    redirect_to root_path if @article.save
  end

  private
    def article_params
      params.require(:article).permit(:item, :description)
    end
end

What am I doing wrong?

2

There are 2 answers

1
Philip Hallstrom On BEST ANSWER

You aren't defining @page in your new action. You need to add something similar to what you've done in create to the new action (and probably the edit action as well).

0
Vitaly Kushner On
before_action :load_page

...

protected
def load_page
  @page ||= Page.find(params[:page_id])
end