Validation only in specific form
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 User
s, but not for new User
s. 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.
精彩评论