methyl
methyl

Reputation: 3312

Validation only in specific form

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

Upvotes: 6

Views: 2337

Answers (3)

DickieBoy
DickieBoy

Reputation: 4956

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.

Upvotes: 1

rdvdijk
rdvdijk

Reputation: 4398

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?.

Upvotes: 4

thomasfedb
thomasfedb

Reputation: 5983

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

Upvotes: 9

Related Questions