2
votes

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
@pradeepDhingra. cannot :filter, Article if user.client? this line should restrict only the client can you please tell us how it is restricting all users?Prabhakar Undurthi
@Prabhakar its not showing Advance Search link for all users..That's my question, it should not restrict all users. Earlier it was showing link for other users except client, but after applying cancan its restricting all users..Pardeep Dhingra

3 Answers

1
votes

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
0
votes

Change the role a bit as following

can :filter, Article unless user.client?

You can read about custom role definition for cancan from here

-1
votes

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.