Search code examples
ruby-on-railscancan

Rails: How to make cancan work on each object?


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?


Solution

  • You can use:

    can :destroy, Business, id: user.auth_ids