In one of my models, I have a before_create attribute that sets a particular value, fetched from a web API. However, this before_create returns false, killing the model creation, if no results are found when using the API.
This works fine, but I would like to also show a warning message, so that the users know their input was not accepted. How would I go about doing this?
A
before_createisn’t the right place to be reporting errors. Yourbefore_createshould try to set the value and then a validator should check if it is there, if the validator doesn’t find the value then you’ll get your error message and such. So, if your attribute is calledpancakes, then you’d have something like this:You could, of course, use a different validator than
validates_presence_of, that’s just there for illustrative purposes. And you’ll want abefore_validationhook to get things to happen in the right order, the:if => :new_record?will only run the hook when you’re creating a new model.