Andrey Deineko
Andrey Deineko

Reputation: 52357

rails prevent object creation in before_create callback

I want to check some attributes of the new record, and if certain condition is true, prevent the object from creation:

before_create :check_if_exists

def check_if_exists
  if condition
    #logic for not creating the object here
  end
end

I am also open for better solutions!

I need this to prevent occasional repeated API calls.

Upvotes: 6

Views: 6834

Answers (2)

Fer
Fer

Reputation: 3347

You can use a uniqueness validator too... in fact is a better approach as they are meant for those situations.

Another thing with the callback is that you have to be sure that it returns true (or a truthy value) if everything is fine, because if the callback returns false or nil, it will not be saved (and if your if condition evaluates to false and nothing else is run after that, as you have written as example, your method will return nil causing your record to not be saved)

The docs and The guide

Upvotes: 4

Ajay
Ajay

Reputation: 4251

before_create :check_if_exists

def check_if_exists
  errors[:base] << "Add your validation message here"
  return false if condition_fails
end

Better approach:

Instead of choosing callbacks, you should consider using validation here.Validation will definitely prevent object creation if condition fails. Hope it helps.

  validate :save_object?
  private: 
   def save_object?
     unless condition_satisifed
       errors[:attribute] << "Your validation message here"
       return false
     end
   end

Upvotes: 14

Related Questions