开发者

Validators before_update(ing) a model

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?

Fo开发者_如何学Gor example:

I have a class Topic and I want to allow only the creator of the Topic to be able to change the title.


# Topic.rb
before_update :your_custom_validation

private
    def your_custom_validation
        # your code
    end

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 devise and only allowing logged in users to do stuff like that, which goes great with a permissions gem called cancan.

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_method callback to fire off with the other validations. If you're not the author, validations fail, nothing gets saved.


You could use http://guides.rubyonrails.org/active_record_validations_callbacks.html#on the before_update comes after the validations fase in ActiveRecord. The link I just posted is very informative. You could use a custom validator with the on option.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜