How to restrict user to search for a particular model in view?

107 views Asked by At

Application I am working has different user roles client, project manager and super user and on landing page they can search for Articles and there is an advanced filter to filter out records after search. Like: Filter by Author.

I want to hide advance filter for client, for that I want to define ability using cancancan.

Currently I am doing it with model methods. These methods return true and false on the basis of user type.

client?
project_manager?
super_user?

Current Code:

<% unless current_user.client? %>
   <%=link_to "Advance Search", "#" %>
<%end%>

I want to remove this and use cancancan instead of this.

<%if can? :filter, Article %>
  <%=link_to "Advance Search", "#" %>
<%end%>

For this I tried

cannot :filter, Article if user.client?

But this is restricting all users to filter.

3

There are 3 answers

6
max On BEST ANSWER

You need to declare a can rule to actually allow users to :filter.

can :filter, Article do |article|
  !user.client?
end

Or

unless user.client?
  can :filter, Article
end

An example of using cannot:

can :friend, User

cannot :friend, User do |other_user|
  other_user.blocks?(user)
end
1
Prabhakar On

Can you try this

# in models/user.rb
def is?(role)
  roles.include?(role.to_s)
end

# in models/articles.rb
can :filter, :all if user.is? :client || :super_user

The above filter will make only the client or super_user can filter the stuff.

0
Rokibul Hasan On

Change the role a bit as following

can :filter, Article unless user.client?

You can read about custom role definition for cancan from here