Showing a warning message when before_create fails?
In one of my models, I have a before_create attribute that se开发者_开发技巧ts 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_create
isn't the right place to be reporting errors. Your before_create
should 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 called pancakes
, then you'd have something like this:
before_validation :stuff_web_api_value_into_pancakes, :if => :new_record?
validates_presence_of :pancakes
You could, of course, use a different validator than validates_presence_of
, that's just there for illustrative purposes. And you'll want a before_validation
hook 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.
精彩评论