Is there no-one out there who can assist with this?
Having problems finding records using cancan in my rails 3.2 app.
In my ‘nas’ index, I’m trying to display a list of ‘nas’ that belong to the current_user’s locations.
The issue seems to be that there’s no formal relationship between the user and the nas – the location owns the nas and the user owns the location.
Using the accessible_by method in my nas controller gives me unusual results. If I use the following in my ability.rb, I get an error :
can :read, Nas, :locationusers => { :user_id => user.id }
Error: undefined method `class_name' for nil:NilClass
And, if I change to:
can :read, Nas, :locations => { :user_id => user.id }
I only get the nas listed for the users first location.
For example, if my user has locations with ids = 1,2,3 only the nas from location 1 are displayed.
Is there a way to display all the nas for the current user’s locations using cancan or do I have to go about this differently?
My relationships are as follows:
class User < ActiveRecord::Base
...
has_many :locationusers
has_many :locations, :through => :locationusers
...
end
class Location < ActiveRecord::Base
...
has_many :locationusers
has_many :users, :through => :locationusers
has_many :nas
...
end
class Node < ActiveRecord::Base
...
belongs_to :location
end
In my ability.rb:
...
if user.role? :customer_admins
can :read, Nas, :locations => { :user_id => user.id }
..
NasController
@nas = Nas.accessible_by(current_ability).all
With Cancan, the User is king. If you cannot draw a line from User to the Model you are trying to authorize, it is not going to work. The easy solution is to model the relationship between
Nas(the model in your example is calledNode?) andUser. This can be done viaLocationuser(which is not shown in your example) as a has_many :through using the existing belongs_to.Now in your Cancan ability.rb, you can use:
(I changed
Nasfrom your example toNodeto correctly match the model)