I want when editing a model to perform some validations so I thought that the best way is to use the
before_update
in Rails.
Can someone provide an example of a custom validator using a before_update call?
For example:
I have a class Topic and I want to allow only the creator of the Topic to be able to change the title.
You can do that with any callbacks. That is, specify the filter and pass it a symbol to the name of your method.
You may also want to consider adding a user authentication gem like
deviseand only allowing logged in users to do stuff like that, which goes great with a permissions gem calledcancan.Edit: (Going to put it here too, even though it’s in the comments below)
I forgot about order of execution. I would still recommend using something like devise and seeing if the right person is logged in (you can authenticate the user in the controller) or using the
validate :custom_methodcallback to fire off with the other validations. If you’re not the author, validations fail, nothing gets saved.