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?
You aren't defining
@page
in yournew
action. You need to add something similar to what you've done increate
to thenew
action (and probably theedit
action as well).