在页面上添加文章时出错

Error adding articles on the page

按照示例 guides.rubyonrails.org/getting_started.html 我在尝试在页面上添加文章时收到错误 nil:NilClass 的未定义方法“文章”。

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

我做错了什么?

您没有在 new 操作中定义 @page。您需要将类似于您在 create 中所做的添加到 new 操作(可能还有 edit 操作)。

before_action :load_page

...

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