4

嗨,我是 ruby​​ on rails 的初学者,我正在使用此参考 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>

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

4

2 回答 2

12

在您的控制器中:

def new
  @post = Post.new
end 

在你的视野中

 <%= 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>

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

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

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

于 2013-08-27T12:45:01.697 回答
3

在您的控制器中:

def new
  @post = Post.new
end

在您看来:

<%= 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>
于 2013-08-27T12:38:45.573 回答