vendredi 29 décembre 2017

Rails, can validate a user crating a record is admin, from the model?

I am attempting to make a new record object invalid if the user_id of the object is associated with an account that is not admin.

In the model I'd like to make a validation checks if the object to be created user_id.admin == true.

Neither of these solutions work:

  validates :user_id, User.find(:user_id).admin?

  before_save :user_is_admin, User.find(self.user_id).admin?

So, my question is, how do I write a validation that looks up the user and checks if they are an admin, and throws an error if they are not?

P.S. I am already doing admin checking in the controller as a before_action, but I'd like to invalidate the object if a non admin user manages to create one somehow...and for testing purposes.

If this isn't a best practice I'd still like to know a bit more about creating validity checks in rails.

Aucun commentaire:

Enregistrer un commentaire