6

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.

methyl
  • 3,272
  • 2
  • 25
  • 34
  • Why are you trying to do this? Maybe we can give a better answer if we know the reasons behind your question. – rdvdijk Sep 25 '11 at 13:46
  • I've got messed User model, not separated from profile, when you register you need to provide only few fields and rest is to fill in from edit user action. – methyl Sep 25 '11 at 13:50
  • Btw you can pass all validations like that: Model.save(false) – emrahbasman Sep 25 '11 at 13:50
  • I'd just point out that this sounds like a bad idea. Validations are there to protect your database from data that makes no sense. – thomasfedb Sep 25 '11 at 13:50
  • I know, but I don't want to rebuild half of application... some basic validations are mantadory. – methyl Sep 25 '11 at 13:53
  • What you *should* be doing is validating them if they are present. Or perhaps using a wizard-style form. – thomasfedb Sep 26 '11 at 04:34

3 Answers3

9

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
thomasfedb
  • 5,990
  • 2
  • 37
  • 65
  • Nope. `@special` is just an instance variable. Unless you have further work to do then you can just let it die, it won't be persisted to further database queries. – thomasfedb Sep 25 '11 at 13:50
4

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

rdvdijk
  • 4,400
  • 26
  • 30
1

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.

DickieBoy
  • 4,886
  • 1
  • 28
  • 47