文章中的NoMethodError#edit in Ruby on Rails教程第5.11节

use*_*261 1 ruby ruby-on-rails

解决这个问题:Ubuntu 12.04 64位,Ruby 2.0.0,Rails 4.1.0

我正在尝试遵循官方的Ruby On Rails教程(http://guides.rubyonrails.org/getting_started.html),但我在第5.11节遇到困难.我看到人们遇到5.12而不是5.11的问题,所以我想我应该问.

这是他们教你如何编辑文件的部分.现在,正如他们所说,我的edit.html.erb文件:

<h1>Editing article</h1>

<%= form_for :article, url: articles_path(@article), method: :patch do |f| %>
  <% if @article.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@article.errors.count, "error") %> prohibited
      this article from being saved:</h2>
    <ul>
    <% @article.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
  <% end %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

<%= link_to 'Back', articles_path %>
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试编辑文件时,出现以下错误:

oMethodError in Articles#edit
Showing /home/aespielberg/RoR/blog/app/views/articles/edit.html.erb where line #4 raised:

undefined method `errors' for nil:NilClass
Extracted source (around line #4):

  <h1>Editing article</h1>

  <%= form_for :article, url: articles_path(@article), method: :patch do |f| %>
    <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@article.errors.count, "error") %> prohibited
        this article from being saved:</h2>

Rails.root: /home/aespielberg/RoR/blog

Application Trace | Framework Trace | Full Trace
app/views/articles/edit.html.erb:4:in `block in _app_views_articles_edit_html_erb__4315770151411025849_69984046087300'
app/views/articles/edit.html.erb:3:in `_app_views_articles_edit_html_erb__4315770151411025849_69984046087300'
Run Code Online (Sandbox Code Playgroud)

现在,我不确定为什么会这样,因为Article继承了:

class Article < ActiveRecord::Base
  validates :title, presence: true,
                    length: { minimum: 5 }
end
Run Code Online (Sandbox Code Playgroud)

据我所知,这应该具有.errors和.errors.any函数.

而我的控制器:

class ArticlesController < ApplicationController

    def new
      @article = Article.new
    end

    def create
      @article = Article.new(article_params)

      if @article.save
        redirect_to @article
      else
        render 'new'
      end
    end

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

    def index
        @articles = Article.all
    end

    private
      def article_params
        params.require(:article).permit(:title, :text)
      end

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

      if @article.update(article_params)
        redirect_to @article
      else
        render 'edit'
      end
    end

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

end
Run Code Online (Sandbox Code Playgroud)

这引出了两个问题:

  1. 为什么会发生这种错误?
  2. 解决这个问题的正确方法是什么?

Mis*_*cha 7

你必须把editupdate方法放在上面private.以下任何内容都是private私有方法edit,update应该是公共方法.