Ruby on Rails中的Object.errors不起作用

时间:2018-05-21 21:52:54

标签: ruby-on-rails ruby

我有一个表单错误partial会在Users#new中引发NoMethodError。它说“nil的未定义方法errors:NilClass

这是我通过以下方式调用的部分内容:<%= render 'shared/error_messages', object: f.object %>

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

new.html.erb的{​​{1}}:

users

<%= simple_form_for :user, url: register_path do |f| %> <%= render 'shared/error_messages', object: f.object %> <%= f.input :username, label: false, placeholder: "Username (maximum: 12 characters)", class: "form-control" %> <%= f.input :first_last_name, label: false, placeholder: "First & Last Name", class: "form-control" %> <%= f.input :email, label: false, placeholder: "Email Address", class: "form-control" %> <%= f.input :password, label: false, placeholder: "Create a Password (minimum: 6 characters)", class: "form-control" %> <%= f.button :submit, "Create an Account!", class: "submit btn btn-block btn-success" %> <% end %>

users_controller

我真的不明白为什么这不起作用,谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

将打开表单的方式更改为此方式(而不是符号传递您在新操作中创建的对象):

<%= simple_form_for @user, url: register_path do |f| %>