0
votes

I am using Devise for registering accounts and signing in/out. The next functionality I want to add is to only show the data entered for a given user. For instance, if I create a new "something" (a client in my case, at /clients/new), I only want the person who created that something to be able to view it. Right now, if I log in and create a new client, then log out and back in as a different user, I'm able to see the client I created as the other user. This should be restricted so that the author is the only one who can read, update and destroy their own clients.

I've watched Ryan Bate's screencast on CanCan 3 times now, but it seems to only touch on setting it up for different roles, and not for limiting content based on the author.

How can I go about this with CanCan?

My current ability.rb has nothing in it but an empty initialize(user) method.

I have tried this inside that method:

can :update, Client do |client|
    client.try(:user) == user
end

with

<% if can? :update, @client %> ... <% end %>

around the loop that displays the clients in the index view, but to no avail.

2
I think you want to reference current_user thereMike Szyndel

2 Answers

1
votes

I think that filtering the results using CanCan is not an optimal solution. If User 'has_many' Clients, then in your controller method just query for Users' clients:

@clients = current_user.clients
0
votes

Give this a try

def initialize(user)
  can :update, Client, :user_id => user.id
end

From cancan wiki