rails 4中未定义的方法`errors'

nil*_*ash 4 ruby-on-rails undefined

嗨,我是初学者在轨道上的ruby,我正在使用这个参考http://guides.rubyonrails.org/getting_started.html开发小型博客应用程序

我在这里面临以下问题.

 <%= form_for :post, url: posts_path do |f| %>
<% if @post.errors.any? %> // Error showing undefined errors method
<div id="errorExplanation">
  <h2><%= pluralize(@post.errors.count, "error") %> prohibited
    this post from being saved:</h2>
Run Code Online (Sandbox Code Playgroud)

我是这个环境的初学者.如何解决这个问题呢.需要帮忙.谢谢.

Raj*_*Das 10

在你的控制器中:

def new
  @post = Post.new
end 
Run Code Online (Sandbox Code Playgroud)

并在您的视图中

 <%= form_for :post, url: posts_path do |f| %>
  <% if @post.errors.any? %>
   <div id="errorExplanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited
         this post from being saved:</h2>
Run Code Online (Sandbox Code Playgroud)

是的,你只需要实例化Post对象....现在在你的情况下,Post没有被实例化以便抛出错误.您还应该知道,错误被定义为实例方法而不是类方法.因此,它将在特定实例上调用.

您可以使用以下链接找到有关活动模型错误的更多信息:

http://api.rubyonrails.org/classes/ActiveModel/Errors.html