From the course: Ruby on Rails 6 Essential Training: Models and Associations

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Execute callbacks conditionally

Execute callbacks conditionally - Ruby on Rails Tutorial

From the course: Ruby on Rails 6 Essential Training: Models and Associations

Start my 1-month free trial

Execute callbacks conditionally

- [Instructor] By default callbacks will run all the time at the point at which you've registered them to execute. But we can also execute callbacks conditionally. And that's what we're going to see in this movie. You can tell your model to execute callback methods only when a particular condition is met. Now you could of course write a condition in the callback itself so that the callback only executed code if that condition was met. But it's often nicer to put it at the top level so it's very clear that the callback is only being called under certain circumstances. We can do that by passing in the if or unless option to the callback. The format looks something like this, after_save throw_a_party that's the method that we're going to call in the after_save. But we're not going to do it every time. We're only going to throw_a_party if change_is_good returns true. The method or the code block that you put after if should…

Contents