16

I want to execute a custom validation before the record is created?

It looks as if this is the right method: before_validation_on_create. For example:

before_validation_on_create :custom_validation

But am not sure. Any help would be appreciated.

1
  • I see there is: validate_on_create. Commented Jun 19, 2010 at 23:28

4 Answers 4

34

In rails 3

before_validation_on_create :do_something

has been replaced with:

before_validation :do_something, :on => :create
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think this addresses the question of running custom validations before creation, but it answers the question I came here with.
20

before_validation_on_create hooks happen before validation on create… but they aren't validations themselves.

What you probably want to do is use validate and a private method which adds to the error array. like this:

class IceCreamCone

  validate :ensure_ice_cream_is_not_melted, :before => :create

  private
    def ensure_ice_cream_is_not_melted
      if ice_cream.melted?
        errors.add(:ice_cream, 'is melted.')
      end
    end
  end

2 Comments

I like your example in particular.
This example has me giggling like a little girl at the office
13

The following worked for me in Rails 5:

validate :custom_validation_method, :on => :create

Running

validate :custom_validation_method, :before => :create

gave me following error:

Unknown key: :before. Valid keys are: :on, :if, :unless, :prepend.

Comments

2

There's a great resource here for information on callbacks and the order they happen in:

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

2 Comments

Why was this downvoted? It points to very clear documentation describing the solution to the OP's problem, and better understanding of validations in general.
It got downvoted because it's not an answer, it's just a link to an external reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.