Rails验证:在创建时跳过格式

时间:2012-11-09 17:31:21

标签: ruby-on-rails validation

Rails正在跳过:create上的格式验证。在创造时,它接受任何东西。然后在更新:presence和:format都按预期工作。我怎么能改变它所以它会:make_blank on create并检查格式呢?

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

1 个答案:

答案 0 :(得分:1)

尝试对:create,:update和所有生命周期事件使用单独的validates语句。当你将它们全部混合在一起时,你的: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