简体   繁体   English

尝试对局部变量使用验证

[英]Trying to use validations with local variables

So I've been trying to use validations on ruby on rails with the form_for format 所以我一直在尝试使用form_for格式在Rails上对ruby进行验证

I followed this: https://stackoverflow.com/a/33048292/8054234 我遵循了这个: https : //stackoverflow.com/a/33048292/8054234

but im getting the following error: 但是我收到以下错误:

<%= pluralize(object.errors.count, "error") %> prevented the form from being saved:

undefined method `errors' for :user:Symbol

Any idead how I could make this work/fix it? 有没有想过我该如何做/解决这个问题?

edit1 uploaded full form code: edit1上传的完整表单代码:

<%= stylesheet_link_tag "users" %>

<div class="jumbotron"
    <div class="container">

    <h2>Signup</h2>


<%= form_for :user, url: '/users' do |f| %>
  <%= form_errors_for :user %>
  Número de Empregado: <br>
  <%= f.number_field :NumeroEmpregado %><br>
  Primeiro e Último Nome: <br>
  <%= f.text_field :nome %><br>
  Password: <br>
  <%= f.password_field :password %><br>
  Confirmação Password: <br>
  <%= f.password_field :password_confirmation %><br>


  <%= f.submit "Submit" %>

    </div>
</div>

<% end %>

object must be an instance of an ActiveRecord model. object必须是ActiveRecord模型的实例。 You are passing :user as a symbol. 您正在传递:user作为符号。

You should pass an instance of User. 您应该传递一个User实例。 If you use some authentication logic you could pass current_user to this method. 如果使用某些身份验证逻辑,则可以将current_user传递给此方法。

UPD: UPD:

The error says that your object does not understand method errors . 该错误表明您的object不了解方法errors :user is a Symbol. :user是一个符号。 It is not a variable that holds your user. 它不是保留用户的变量。 Therefore, it does not implement method errors . 因此,它不会实现方法errors

User is a model that inherits behaviour from ActiveRecord . User是从ActiveRecord继承行为的模型。 It provides method errors . 它提供方法errors For example, object = User.create(params) will work. 例如, object = User.create(params)将起作用。

EDITED 已编辑

In your UsersController in new action update as below 在您的UsersController中,进行new操作,如下所示

class UsersController < ApplicationController
  def new
    @user = User.new
  end
end

and in your views/users/_form.html.erb file form do the below code 并在您的views/users/_form.html.erb文件表单中执行以下代码

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
    <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
    <ul>
      <% @user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
    </ul>
    </div>
  <% end %>

  Número de Empregado: <br>
  <%= f.number_field :NumeroEmpregado %><br>

  Primeiro e Último Nome: <br>
  <%= f.text_field :nome %><br>

  Password: <br>
  <%= f.password_field :password %><br>

 Confirmação Password: <br>
 <%= f.password_field :password_confirmation %><br>

 <%= f.submit "Submit" %>

<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM