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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With