Pedram
Pedram

Reputation: 234

Rails custom validation involving current_user

I have been developing a rails app in which we allow different users to submit different values for an attribute of a model.

For example all users can submit values greater than 10 while administrators are allowed to submit one-digit values as well.

As we know models do not have access to the current_user helper, therefore you can not write a custom validator with ease.

What's the best practice when implementing such a feature?

Upvotes: 3

Views: 2662

Answers (3)

iconoclast
iconoclast

Reputation: 22610

This is a perfect use case for validation contexts. You define the contexts in your model, but then your controller specifies which context to use.

Here is a nice article by Justin Weiss about them—although he doesn't mention that they solve problems not solved well any other way, per-user validation rules being the perfect example, since your model doesn't have access to the current user, and your controller isn't designed to specify validation rules:

https://www.justinweiss.com/articles/a-lightweight-way-to-handle-different-validation-situations/

Upvotes: 3

margo
margo

Reputation: 2927

This is probably a case where you enforce the validation in the controller. Strictly speaking this is not about model validation, but about user authorisation. Pundit is a nice gem for authorisation or you can roll your own.

Upvotes: 0

Alfie
Alfie

Reputation: 2784

It's always advised to keep logic like current_user outside your model. But given your requirement,

Well, as our controller knows current_user then it should be the controller that tells your model about it.

So in your model add an attr_accessor for current_user and in your controller do something like

@model_obj.current_user = current_user

Now all this being said. I'd propose using an alternative to model validation. Because in real what you are trying to do is giving users permissions based on their role. You'd be better of using a gem like Pundit for it.

Upvotes: 1

Related Questions