【发布时间】:2014-04-29 19:24:13
【问题描述】:
Ruby on Rails 菜鸟在这里学习 RoR.org 上的入门教程。我在“5.11 添加一些验证”部分,尝试刷新 /posts/new 页面时出现错误:
错误信息:
NoMethodError in PostsController#new
undefined method ` validates' for #<Class:0x0000000414fab0>
Extracted source (around line #2):
1 class Post < ActiveRecord::Base
2 validates :title, presence: true,
3 length: { minimum: 5 }
4 end
我的帖子.rb:
class Post < ActiveRecord::Base
validates :title, presence: true,
length: { minimum: 5 }
end
我的 posts_controller.rb:
class PostsController < ApplicationController
def index
@posts = Post.all
end
def new
@post = Post.new
end
def create
@post = Post.new(params[:post].permit(:title, :text))
if @post.save
redirect_to @post
else
render 'new'
end
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :text)
end
end
旁注 - FWIW,在尝试诊断此问题时,我从 posts_controller.rb 中删除了 @post = Post.new,刷新时出现此错误:
undefined method `errors' for nil:NilClass
Extracted source (around line #3):
<h1>New Post</h1>
<%= form_for :post, 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>
找不到等式的 new.html.erb 部分有任何问题,因此我正在向社区寻求指导。有人知道我哪里出错了吗?提前感谢您的帮助。
【问题讨论】:
-
Model validation 的可能重复项
标签: ruby-on-rails validation ruby-on-rails-4