在 Rails 中创建期间跳过一些验证,但运行其他验证
我想在创建新用户期间跳过一些属性的验证,例如地址、密码、电话号码等。
但是,当用户尝试编辑模型时,它仍然需要在模型中进行其他验证。我尝试使用 :on => :更新但这对我没有帮助。有什么建议吗?
我的代码:
validates :address, :presence => true, :length => { :maximum => 50 }, :on => :update
validates :city, :presence => true, :length => { :maximum => 50 }, :on => :update
validates :state, :presence => true, :length => { :maximum => 50 }, :on => :update
validates :zip, :presence => true, :numericality => true, :on => :update, :length => { :is => 5 }
I want to skip the validations of few attributes during creation of a new user like address, pin, phone number etc.
However, it still need to do the other validations in the model when user tries to edit it. I tried using :on => :update but that doesn't help me. Any suggestions ?
My Code:
validates :address, :presence => true, :length => { :maximum => 50 }, :on => :update
validates :city, :presence => true, :length => { :maximum => 50 }, :on => :update
validates :state, :presence => true, :length => { :maximum => 50 }, :on => :update
validates :zip, :presence => true, :numericality => true, :on => :update, :length => { :is => 5 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据文档,您需要做的是这样的。你是说这行不通吗?
According the the documentation, what you need to do is something like this. Are you saying this is not working?
请注意,如果存在数据库限制,您仍然会收到错误消息。
例如,如果您使用 Rails 迁移并具有
:null => false
创建时(通过运行迁移),实际数据库列将在数据库级别具有该限制。一件好事是验证应该在两个地方进行。覆盖数据库约束(即不能)的方法是迁移以实际删除约束。Note that is there are database constraints you'll still get an error.
e.g. if you use a rails migration and have
:null => false
when it is created (by running the migration) the actual database column will have that restriction be at the database level. A good thing as validations should be in both places. The way to override the db constrainst (i.e. you can't) would be a migration to actually remove the constraint.创建记录时:
这将跳过验证。
On creation of record:
This will skip the validation.
添加 if=> :属性改变了?将解决问题。
Adding if=> :attribute_changed? will solve the problem.