开发者

Validation only in specific form

开发者 https://www.devze.com 2023-04-07 02:47 出处:网络
Is there any way to trigger validation only in specific forms(controller\'s action), not globally at every save o开发者_开发技巧r update?

Is there any way to trigger validation only in specific forms(controller's action), not globally at every save o开发者_开发技巧r update? Something like User.create(:validate=>true) flag.


Yes, you can supply conditionals to the validations, eg:

validates_presence_of :something, :if => :special?

private

def make_sepcial
  @special = true
end

def special?
  @special
end

Now all you have to do to turn on these validations is:

s = SomeModel.new
s.make_special


As you explained in the comments, you want to skip validation for new records. In that case, you can use thomasfedb's answer, but don't use the @special variable, but:

validates_presence_of :something, :if => :persisted?

This will validate only for saved Users, but not for new Users. See the API documentation on persisted?.


This is a bit old. But I found http://apidock.com/rails/Object/with_options to be a good way of handling this sort of behaviour.

0

精彩评论

暂无评论...
验证码 换一张
取 消