1

Rails 在创建时跳过 :format 验证。在创建时,它接受任何东西。然后更新 :presence 和 :format 都按预期工作。我该如何更改它,以便在创建时 :allow_blank 并检查格式?

validates :mail, :allow_blank => true, :on => :create,
                 :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)*[a-z]{2,})$/i },
                 :length => { :maximum => 60 },
                 :presence => true, :on => :update
4

1 回答 1

1

尝试validates对 :create、:update 和所有生命周期事件使用单独的语句。当您将它们放在一起时,您的:on => :update选择本质上是覆盖选项。:on => :create

validates :mail, :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)*[a-z]{2,})$/i },
                 :length => { :maximum => 60 }

validates :mail, :allow_blank => true, :on => :create,

validates :mail, :presence => true, :on => :update
于 2012-11-09T17:37:32.670 回答