【问题标题】:Getting undefined method `errors' for nil:NilClass获取 nil:NilClass 的未定义方法“错误”
【发布时间】:2013-12-28 22:19:04
【问题描述】:

我正在http://guides.rubyonrails.org/getting_started.html 学习 Ruby on Rails 教程

但是,当我进入“5.11 添加一些验证”时,添加错误消息以在我尝试从索引视图创建新帖子时显示后,我得到了

“nil:NilClass 的未定义方法‘错误’”

这是突出显示的错误行。

我已经在控制器的新操作中创建了一个新帖子。

这里是源码

new.html.erb

<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>
      <% @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 :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
  <% end %>

posts_controller.rb

class PostsController < ApplicationController
def new
    @Post = Post.new
end

def create
    @post = Post.new(post_params)
    if @post.save
        redirect_to @post
    else
        render 'new'
    end
end

def show
    @post= Post.find(params[:id])
end

def index
    @posts = Post.all
end

def edit
    @post = Post.find(params[:id])
end

def update
    @post = Post.find(params[:id])

    if @post.update(post_params)
        redirect_to @post
    else
        render 'edit'
    end
end

private
    def post_params
        params.require(:post).permit(:title, :text)
    end
end

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    改变

    @Post = Post.new
    

    @post = Post.new
    

    微妙但致命

    【讨论】:

    • 非常感谢。这让我发疯了。
    【解决方案2】:

    你的控制器有错误:

    def new
        @Post = Post.new
    end
    

    只需将@Post 更改为@post。

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 2012-12-27
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多