I'm new to Rails and exercising. I have two user models, Student and Prof. I added an admin role to the Student model with enum.
I want to allow a Prof's profile to be edited by the owner of the profile or an admin.
Here is my code in profile_policy.rb:
def update?
is_owner? || user.admin? if user
end
[...]
def is_owner?
record.prof == user
end
and in my show view, I want to show the link "edit" only based on the Pundit authorization:
<%= link_to 'Edit', edit_prof_profile_path(@prof.id, @profile.id) if policy(@profile).edit? %>
In my application controller I have a custom current_user method that includes both current_student and current_prof.
The problem is that user.admin?
calls the admin method on the Prof model, which doesn't have such method, so I get the error undefined method admin?
when a Prof who isn't the owner wants to visit a profile.
How can I fix that?
This is a solution that eventually worked for me, using try()
In my policy file, I add this custom method checking if the user has or not a role
defined as "admin
. This method will return true
or false
, as expected by Pundit.
def is_admin?
user.try(:role) == "admin"
end