2

I have validate method in my model

def validate
  super    
  if some condition
    errors.add('', 'some text')
  end
end

This method call on Create and Update. I don't want to call on Update. How can I do that?

I am using rails2.3.11 and jruby.

Update: I can use this one validate :custom_validation, :on => :create, but How they called on Create and Update??

I also checked validate_on_create, but still I am not figureout when this validate called?

2 Answers2

7

Use

validate :custom_validation, :on => :create

and change your method name from validate to custom_validation i.e.

def custom_validation
  super    
  if some condition
    errors.add('', 'some text')
  end
end

and the above method will call only on create and not on update

Salil
  • 46,566
  • 21
  • 122
  • 156
0

Using :on => :create, for me had unexpected results in an older application running Rails 4.2.5.1

I would not expect my below validation to be called when I called .valid? but it was being called.

a) My Test Model contained `validate :exec_on_create, :on => :create`.
b) In console
001 > t = Test.new(msg: '7 ...')
002 > t.valid?
******* "exec_on_create" was called.
=> true

Changing :on => :create to before_create :exec_on_create, performed more to what I would expect ... no longer called the validation that was supposed to be called only on create.

a) My test Model contained `before_create :exec_on_create`.
b) In console
001 > t = Cals2Db::Test.new(msg: '7 ...')
002 > t.valid?
=> true
Chris
  • 380
  • 5
  • 10