簡體   English   中英

如何繞過 validates_email_format_of 驗證以保存零 email 值?

[英]How can I bypass validates_email_format_of validation to save nil email value?

在 Rails 4 應用程序的多個地方,validates_email_format_of gem 是完美的解決方案。 但是當 email 地址反彈時,我想將 nil 值保存到 email 字段。

在我的 Gemfile 中:

gem 'validates_email_format_of', git: 'https://github.com/alexdunae/validates_email_format_of.git'

在我的用戶 model 中:

validates_email_format_of :email, :message => 'Email format looks invalid. Did you mistype?'

在我看來:

<%= button_to 'Delete this Email Address', delete_email_addy_admin_path(user.id), data: { confirm: 'Are you sure?'}, class: "btn_danger" %>

在 controller 中:

def delete_email_addy
   @user = User.find(params[:id])
   @user.email = nil
   @user.save!
   redirect_to email_bounces_admins_path
end

結果是產生了我的消息“電子郵件格式看起來無效...”。 使用 update_attributes 而不是 save 或 save。 導致回滾到之前的值。

根據gem 文檔,它同時支持:allow_nil:allow_blank選項。 所以:

validates_email_format_of :email, 
                          :message => 'Email format looks invalid. Did you mistype?',
                          :allow_nil => true

編輯回答您的后續問題

如果你想有時允許nil有時不允許,它還支持:if:unless選項。 您不需要 model 來了解有關 controller 的任何信息(您也不應該)。 您只需將非持久性 boolean 屬性添加到 Model ,然后使用:if/:unless進行檢查。

model

class YourModel < ActiveRecord::Base
  attr_accessor :skip_email_validation

  validates_email_format_of :email, 
                            message: 'Email format looks invalid.',
                            unless: -> { skip_email_validation? }
  ...
end

controller

def delete_email_addy
   @user = User.find(params[:id])
   @user.email = nil
   @user.skip_email_validation = true
   @user.save!
   redirect_to email_bounces_admins_path
end

快速查看@Karl 的 gem 表明它可以自動執行添加這些非持久屬性的過程。 如果您有很多情況需要有條件地跳過驗證和/或不介意額外的 gem,那么超級,但對於單個情況,您自己滾動可能同樣容易。

看起來你可以使用:

validates_email_format_of :email,
    :message => 'Email format looks invalid. Did you mistype?',
    :allow_nil => true

使用allow_nil: true是允許nil的簡單處理,但我有一個validation_skipper gem可以處理更復雜的需求。

從我的Gemfile

# Rails gem that lets you skip validations
gem 'validation_skipper', '>= 1.3.0', github: 'K-and-R/validation_skipper'

使用這個 gem,你可以有更復雜的邏輯來確定何時跳過驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM