0

Hi I have this concern in model/concerns/permissions_concern

This check my users table and permission_level column which is type integer.So if user has admin privileges I want him to be able to access in Navbar an specific link

module PermissionsConcern
    extend ActiveSupport::Concern
    def is_normal_user?
      self.permission_level >= 1
    end

    def is_editor?
      self.permission_level >= 2
    end

    def is_admin?
      self.permission_level >= 3
    end 
end

I want to know if is possible to call a module to an erb page so for example:

<li class="nav-item">
  <% if is_admin? %>
         <%= link_to "Dashboard", articles_path, class: 'nav-link' %>
    <%else%> 
         <li class="nav-item">
         <%= link_to 'Login', new_user_session_path, class: 'btn btn-outline-success' %>
         </li>
         <li class="nav-item">
      <%= link_to 'Register', new_user_registration_path, class: 'btn btn-outline-info' %>
         </li>
  <%end%>

</li>

But I get this error

undefined method `is_admin?' for #<#:0x007f962f818680> which is okay because is not a method. But is there a way to call a concern in an erb page?

jean182
  • 1,506
  • 2
  • 9
  • 19

2 Answers2

1

If it's in a concern you need to include that or specify the full path:

 if PermissionsConcern.is_admin?

The thing is, you probably want to make that a helper instead if you're intending to use it inside views. Those references to self will be meaningless inside a bare concern.

tadman
  • 194,930
  • 21
  • 217
  • 240
1

To add a little context to tadman's answer, concerns are typically used to consolidate methods used by several models. That doesn't look like what you're trying to accomplish. It looks like you're trying to simplify your view logic. To do that, helpers are the way to go. So you'll need a way for is_admin? to find the user who is currently logged in and check their permission level.

You have an application-wide helper file called application_helper.rb. Instead of having is_admin? in a concern (that I'm assuming is included in your User model), you could put it in application_helper.rb and it will be available to all your views. But you'll have a problem! The is_admin? method won't know about the user so it'll blow up. If you're using Devise for authentication, you should have a current_user method which references the person that's logged in. You can change your is_admin? method in your application_helper.rb file to:

def is_admin?
  current_user.permission_level >= 3
end

And you should be all set. Good luck!

More info on concerns: https://stackoverflow.com/a/25858075/320490

Community
  • 1
  • 1
Chachi
  • 63
  • 6