gpt4 book ai didi

ruby-on-rails - 为 nil :NilClass on the view new 获取未定义的方法 `errors'

转载 作者:数据小太阳 更新时间:2023-10-29 08:44:35 24 4
gpt4 key购买 nike

我是 ruby​​ 的新手,正在学习,所以我一直在学习本教程 http://guides.rubyonrails.org/getting_started.html但是当我尝试添加错误消息时,我得到了 nil:NilClass 的未定义方法“错误”在这段代码中:

<h1>New Article</h1>
<%= form_for :posts, url: posts_path do |f| %>
<% if @post.errors.any? %> // <-- **HERE**
<div id="error_explanation">
<h2>
<%= pluralize(@post.errors.count, "error") %> prohibited

这是我的 Controller :

class PostsController < ApplicationController
def index
@posts = Post.all
end

def new
@posts = Post.all
end

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

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

private
def posts_params
params.require(:posts).permit(:title, :description)
end
end

我的观点完全错误:

<h1>New Article</h1>
<%= form_for :posts, 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 :description %><br>
<%= f.text_area :description %>
</p>

<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', posts_path %>

My model:



class Post < ActiveRecord::Base

validates :title,
:presence => {:message => "Title can't be blank." },
:uniqueness => {:message => "Title already exists."},
length: { minimum: 5 }

validates :description,
:presence =>{:message => "Description can't be blank." }
end

有人可以帮助我吗?

最佳答案

您有以下内容:

<% if @post.errors.any? %>

但是在你的 Controller 中,你有:

 def new
@posts = Post.new
end

def create
@posts = Post.new(posts_params)
...
end

在 Controller 中将 @posts 重命名为 @post

因此,代码必须如下所示:

def new
@post = Post.new
end

def create
@post = Post.new(posts_params)
...
end

关于ruby-on-rails - 为 nil :NilClass on the view new 获取未定义的方法 `errors',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33529727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com