Rails: How to make cancan work on each object?

155 Views Asked by At

user.rb

def has_delete_role? name
  roles.each do |n|
    return true if n == name
  end
end

ability.rb

if user.has_delete_role? :business_delete
  can :destroy, Business
end

index.html.erb

<% if can? :destroy, @business %>
  <%= link_to 'delete', business_path(@business.id), method: :delete%>
<% end %>

This piece of code allow user who has the authority to access delete button. Here if a user has authority, he can access delete buttons of all objects.

EX: Business has 10 objects id = 1 to id = 10, user can access all of 10 delete buttons if he has the authority

But now I want to set the authority base on object.

EX: Buisness also 1 to 10, user can only see button 2 and 5 because there is a field in user data table called auth_ids [], it stores [2,5]

How to achieve this?

2

There are 2 best solutions below

4
On BEST ANSWER

You can use:

can :destroy, Business, id: user.auth_ids
1
On

You can set up a condition, something similar to the guide here: https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities

can :destroy, Business, Business.where('id = ?', user.auth_ids)