得到這個出路:Ubuntu的12.04 64位,紅寶石2.0.0,Rails的4.1.0NoMethodError在Ruby的文章#編輯on Rails的教程部分5.11
我試圖按照官方的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 %>
當我嘗試編輯一個文件,不過,我得到以下錯誤:
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'
現在,我不知道這是爲什麼,因爲文章繼承:
class Article < ActiveRecord::Base
validates :title, presence: true,
length: { minimum: 5 }
end
其中,據我瞭解,應該有.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
這使我兩個問題:
- 爲什麼這個錯誤發生?
- 解決此問題的正確方法是什麼?
噢,我覺得很蠢。謝謝!! – user650261
沒問題。別客氣。 – Mischa