"control-label" %> "form-control" %> 但是当-6ren">
gpt4 book ai didi

ruby-on-rails - Ruby on Rails 在特定字段中存在错误

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

我正在定义对存在于名为“联系人”的表中的一些字段的验证:

class Contact < ActiveRecord::Base
validates :nome, :cognome, :indirizzo_abitazione,
:numero_civico, :indirizzo_email, :prefisso_cellulare, :cellulare, presence: true
validates :nome, :cognome, :indirizzo_email,
:prefisso_cellulare, :cellulare, uniqueness: true
validates :indirizzo_email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
end

如果出现错误,我想利用 Bootstrap 的类属性“has-error”以红色突出显示特定字段;所以我试着这样做:

  <div class="form-group <%= @contact.errors[:name] ? "has-error" : "" %>" >
<%= f.label :name , :class => "control-label" %><br>
<%= f.text_field :name, :class => "form-control" %>
</div>

但是当我登录到这个页面时,该字段已经是红色的。有没有一种方法可以查看在验证一条记录期间特定字段是否出现错误?

最佳答案

@contact.errors[:name] 返回一个消息数组,如果里面没有消息,那么 @contact.errors[:name] 将只返回一个空的大批。数组是一个对象,因此您的语句将始终产生 "has-error"

这会起作用:

<%= @contact.errors[:name].present? ? "has-error" : "" %>

关于ruby-on-rails - Ruby on Rails 在特定字段中存在错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31140923/

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