加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – “调用错误方法时,”nil:NilClass“的”undef

发布时间:2020-12-16 20:37:43 所属栏目:百科 来源:网络整理
导读:我目前正在教自己一些RoR和做教程,但是添加一些更好的布局和引导的东西,我遇到一个我无法想出的问题. 我试图做验证部分(http://guides.rubyonrails.org/getting_started.html#adding-some-validation),但是当我使用: % @post.errors.any? % 我收到这个消息
我目前正在教自己一些RoR和做教程,但是添加一些更好的布局和引导的东西,我遇到一个我无法想出的问题.

我试图做验证部分(http://guides.rubyonrails.org/getting_started.html#adding-some-validation),但是当我使用:

<% @post.errors.any? %>

我收到这个消息:

undefined method `errors' for nil:NilClass
Extracted source (around line #9):
<legend><h1>Add Post</h1></legend>

<%= form_for :post,url: posts_path,html: {class: 'form-horizontal'} do |f| %>
      <% if @post.errors.any? %>
        <div id="errorExplanation">

没有什么工作,我甚至复制和粘贴教程中的部分.

以下是该视图的代码:

<p> </p>

<div class="span6"

<fieldset>
    <legend><h1>Add Post</h1></legend>

    <%= form_for :post,html: {class: 'form-horizontal'} do |f| %>
          <% if @post.errors.any? %>
            <div id="errorExplanation">

                <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 %>
        <div class="control-group">
            <%= f.label :title,:class => 'control-label' %>
            <div class="controls">
                <%= f.text_field :title,:class => 'span4' %>
            </div>
        </div>

        <div class="control-group">
            <%= f.label :content,:class => 'control-label' %>
            <div class="controls">
                <%= f.text_area :content,:rows => '7',:class => 'input-block-level' %>
            </div>
        </div>

        <div class="form-actions">
            <%= f.submit "Add Post",:class => 'btn btn-success' %>
            <%= link_to "Cancel",posts_path,:class => 'btn',:style => 'float:right;' %>
        </div>
    <% end %>
</fieldset>

</div>

和我的posts_controller:

class PostsController < ApplicationController

    def new
    end

    def create
        @post = Post.new(params[:post].permit(:title,:content))

        if @post.save
            redirect_to @post
        else
            render 'new'
        end
    end

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

    def index
        @posts = Post.order("created_at desc")
    end

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

end

我失踪了什么提前致谢!

解决方法

您还需要在新操作中定义@post.
def new
  @post = Post.new
end

你得到NilClass错误,因为@post没有值(它是零),当你第一次加载表单在新的动作.

当您执行渲染时:创建操作中的新内容没有问题,因为它使用您在创建顶部定义的@post.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读