I’m using Cancan, Devise, Rails 3 for my ordering application.
Each user has many companies through agreements. Each company also has many users through agreements.
In my ability model, I have the following:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :super
can :manage, :all
elsif user.role? :admin
can :manage, [User, Company, Order]
elsif user.role? :tech
can :manage, [User, Company, Tech]
elsif user.role? :customer_admin
can [:read, :update], User, :id => user.id
can [:read, :update], Company, :id => user.id
can [:read ], Order, :id => user.id
end
end
end
When a customer_admin logs in, I’ve been trying to show them only the companies they’re associated with. In the company views, I can see the list of users just fine.
In my companies controller (index), I’ve tried doing this:
@usercompanies = Company.where(['user_id = ?', current_user.id ])
However, this lists the wrong company?!
Am sure this is a silly newbie mistake but would appreciate your help. If you need anything else, let me know.
You can add restrictions with cancan very quickly and it was puzzling the first time I had to set it up as well. The documentation for setting this up is here. And just as a reference you want to make your index action in your controller look something like this:
However in the latest version of the gem this should be done automatically on the index action. I think that you have a mistake in your
abilities.rbbecause when you have a record and you assoicate it with a user it usually has a collumn called user_id. You would want to use that like so:Since the attribute
idnormally is used as the unique id of the record and not the id of the association.