Ruby on Rails noob here taking the Getting Started tutorial on RoR.org. I'm at section "5.11 Adding Some Validation", and am thrown an error when trying to refresh the /posts/new page:
The error message:
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
my post.rb:
class Post < ActiveRecord::Base
  validates :title, presence: true,
                    length: { minimum: 5 }
end
my 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, when trying to diagnose this, I removed @post = Post.new from posts_controller.rb, and when refreshing, got this error:
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>
Couldn't find anything wrong with the new.html.erb part of the equation, so I'm turning to the community for guidance. Anyone know where I am going wrong? Thanks in advance for your help.
After literally banging my head against the table for 30 minutes, and recreate the app three times because I thought I might've made some typo, this is what the problem is:
NoMethodError (undefined method ` validates' for #)
Notice that big gap between the first quote and validates? --> ` validates'
Yeah, that's it. When you copy and paste the code from the site, whatever that @#$%^&* character came with it. I've copied plenty other codes from the same tutorial as well, and it all worked great.
So the fix is to replace the invisible characters before "validates" with a space or a tab.
Great way to "Getting Started with Rails". Just Great™. Rails, must be great™.
You should use validate (without s) instead of validates. See this:
The problem you're running into is probably related to my mysterious and mistaken deployment of the Rails 3 tutorial. The
validatesmethod is specific to Rails 3. Try refreshing your browser to see the correct Rails 2.3 version and I think things will work better. Sorry for the confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With