Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 819
Andrey Deineko Avatar asked Jan 20 '15 09:01

Andrey Deineko


2 Answers

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
like image 166
Ajay Avatar answered Oct 16 '22 08:10

Ajay


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

like image 33
Fer Avatar answered Oct 16 '22 10:10

Fer