0

I have a moderator relationships table which assigns users as mods to groups by pairing their user id with the group id in the table.

I want only mods to be able to create a group.

I am trying to use the pundit gem to do this but i'm stuck on the documentation. It has in its PostPolicy example:

def update?
 user.admin?
end

Is the admin method previously defined somewhere else?

and if it is why don't people just use that in the controller update method directly? e.g.

def update
 if user.admin? 
   update
 else
   dont update
end

I'm building an app to learn rails. Need help wrapping my head around this one. I'm not sure if the pundit gem defines the admin method inside the policy class by itself or if i have to make the method. If i need to make the method why would I need the pundit gem when i can just use the admin method like in the example i did above?

Rob
  • 1,835
  • 2
  • 25
  • 53
  • this post answers my question: http://stackoverflow.com/questions/22213152/where-is-user-admin-defined-in-rails-devise-pundit-starter-app – Rob Jan 05 '16 at 01:58

1 Answers1

1

I didn't use pundit, but seems like I can clarify your questions.

Is the admin method previously defined somewhere else?

Most likely it is just a user attribute: true for admins, false for others.

and if it is why don't people just use that in the controller update method directly?

This is done to decouple authorization and inner action logic, it is a good solution which respects single responsibility principle. Authorization could be complex and you sometimes would want to reuse the rules you defined.

def update
  if user.admin? 
    update
  else
    don't update
  end
end

First of all, how would you handle else case yourself and how long would be your logic? Now imagine you need to repeat this else logic in every action. Furthermore what if you have a user group which can access 10 actions in different controllers, how many times you would repeat those if conditions and else logic?

If i need to make the method why would I need the pundit gem when i can just use the admin method like in the example i did above?

No one forces you to use this gem, it is done to make your life as a developer easier. If your app is relatively small and you don't need such an overkill, advanced options and helpers you are free to write it in your way(for example if you have only admin/not admin options - before_action with a simple check is absolutely enough). The example you are asking about is the most simple case of the gem usage.

Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
  • Thanks for the comment. Found my answer here http://stackoverflow.com/questions/22213152/where-is-user-admin-defined-in-rails-devise-pundit-starter-app – Rob Jan 05 '16 at 01:57