Rails form validation is designed to go in the model most easily. But I need to make sure the current user has the required privileges to submit a post and the current_user variable is only accessible in the controller and view.
I found this answer in a similar question:
You could define a
:user_goldvirtual attribute forBook, set it in the controller where you have access tocurrent_userand then incorporate that into yourBookvalidation.`
How can I set this up with my post and user controller so that the current_user variable is accessible in the model?
Solution:
This whole thing is wrong from an application design perspective as @Deefour’s answer pointed out. I changed it so my view doesn’t render the form unless the condition is true.
The “similar question” is saying you can do something like this
and then in your controller action you can do something like
You can then use
self.current_userwithinYourModel‘s validation methods.Note I don’t think this is what you should be doing though, as I don’t consider this “validation” as much as “authorization”. An unauthorized user shouldn’t even be able to get the part of your action where such an update to a
YourModelinstance could be saved.As for doing the authorization with Pundit as requested, you’d have a file in
app/policies/your_model.rbInclude Pundit in your
ApplicationControllerThen, in your controller action you can do simply
The
authorizemethod will callYourModelPolicy‘supdate?method (it calls the method matching your action +?by default) and if a falsy value is returned a 403 error will result.