我怎么能跳过一个特定的验证导入数据时? [英] How can I skip a specific validation when importing data?
问题描述
如何跳过一个特定的模型验证导入数据时?
How can I skip a specific model validation when importing data?
例如,假设我有这个模型:
For example, suppose I have this model:
class Account
validates :street_address, presence: true
end
通常情况下,我不希望帐户被保存没有地址,但我也将大量数据从旧系统转换,许多帐户有没有地址。
Normally, I don't want accounts to be saved without addresses, but I'm also going to convert a lot of data from an old system, and many accounts there don't have addresses.
我的目标是,我可以添加旧账到新的数据库,但在未来,当这些帐户进行编辑,街道地址将被添加。
My goal is that I can add the old accounts to the new database, but in the future, when these accounts are edited, a street address will have to be added.
正如我所说的,我想跳过一个具体的确认;人还是应该运行。例如,如果没有一个帐号帐号不应该在所有加载到新系统。
As I said, I want to skip a specific validation; others should still run. For example, an account without an account number shouldn't be loaded into the new system at all.
推荐答案
这应该工作:
class Account
attr_accessor :importing
validates :street_address, presence: true,
unless: Proc.new { |account| account.importing }
end
old_system_accounts.each do |account|
# In the conversion script...
new_account = Account.new
new_account.importing = true # So it knows to ignore that validation
# ... load data from old system
new_account.save!
end
这篇关于我怎么能跳过一个特定的验证导入数据时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!