【发布时间】:2015-11-05 16:38:21
【问题描述】:
我是 ruby 新手,我正在学习,所以我一直在学习这个教程 http://guides.rubyonrails.org/getting_started.html 但是当我尝试添加错误消息时,我得到 nil:NilClass 的未定义方法“错误” 在这段代码中:
<h1>New Article</h1>
<%= form_for :posts, url: posts_path do |f| %>
<% if @post.errors.any? %> // <-- **HERE**
<div id="error_explanation">
<h2>
<%= pluralize(@post.errors.count, "error") %> prohibited
这是我的控制器:
class PostsController < ApplicationController
def index
@posts = Post.all
end
def new
@posts = Post.all
end
def create
@posts = Post.new(posts_params)
if @posts.save
redirect_to @posts
else
render 'new'
end
end
def show
@posts = Post.find(params[:id])
end
private
def posts_params
params.require(:posts).permit(:title, :description)
end
end
这是我的观点,它给了我一个完整的错误:
<h1>New Article</h1>
<%= form_for :posts, url: posts_path do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@post.errors.count, "error") %> prohibited
this post from being saved:
</h2>
<ul>
<% @post.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 :description %><br>
<%= f.text_area :description %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', posts_path %>
My model:
class Post < ActiveRecord::Base
validates :title,
:presence => {:message => "Title can't be blank." },
:uniqueness => {:message => "Title already exists."},
length: { minimum: 5 }
validates :description,
:presence =>{:message => "Description can't be blank." }
end
有人可以帮我吗?
【问题讨论】:
标签: ruby-on-rails ruby