微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – “未定义的方法`验证’”错误 – RoR Tut 5.11添加一些验证

Ruby on Rails noob在这里参加了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,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

Sidenote – 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部分的任何问题,所以我转向社区寻求指导.谁知道我哪里出错了?在此先感谢您的帮助.

解决方法

在将我的头撞在桌子上30分钟之后,并重新创建应用程序三次,因为我认为我可能会犯一些拼写错误,这就是问题所在:

NoMethodError(未定义的方法`验证’为#)

请注意,第一个引用和验证之间的差距很大? – > ‘验证

是的,就是这样.当您从网站复制并粘贴代码时,无论@#$%^& *字符随附了什么.我也从同一个教程中复制了很多其他代码,这一切都很有效.

因此,修复方法是在使用空格或制表符“验证”之前替换不可见字符.

“Rails入门”的好方法. Just Great™. Rails,一定很棒.

原文地址:https://www.jb51.cc/ruby/269554.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐