-1

I should check if my User exists and whether the user is an organizer or an admin. Those two columns are boolean in my table Users. How can I deal with it purely? This code works incorrectly:

 <% if current_user.try(:organizer?, :admin?) %>

If I use or for if statement, it works well.

<% if current_user.try(:organizer?) or current_user.try(:admin?) %>
sawa
  • 165,429
  • 45
  • 277
  • 381
Val-Lee
  • 25
  • 6

1 Answers1

3

I'd use

<% if current_user.try(:organizer?) || current_user.try(:admin?) %>

if you do not need something like this a lot. If you often need permission checks you might want to look into a tool that supports you with this. cancancan or pundit comes to mind.

If you want to avoid those ored checks, and don't want to add pundit or thelikes to your stack, you could add another method to your user model:

def admin_or_operator?
  admin? || operator?
end

and then just use that. The feasibility of this approach of course depends on the number of different roles and combinations you need to check.

Also: if you often need to check for the presence of a user (the reason you actually need try) then you could consider using the nil object pattern.

def current_user
  find_actual_user || Guest.new
end

Where Guest would be an object that responds false to all those permission checks.

Also some guidelines:

If you want to know more about the reasons for above recommendations you can check stackoverflow or google.

Pascal
  • 8,464
  • 1
  • 20
  • 31