ryanb / cancan

Authorization Gem for Ruby on Rails.
MIT License
6.27k stars 784 forks source link

How to define conditions in ability for belongs_to, has_many association? #759

Open zhaohuic opened 11 years ago

zhaohuic commented 11 years ago

My two associations:


class Project < ActiveRecord::Base belongs_to :user end

class User < ActiveRecord::Base include ActiveModel::MassAssignmentSecurity has_many :projects

list of attributes that lab_admin can modify

attr_accessible :login, :cost_center, :last_name, :lab_admin, :as => :lab_admin end


And in my ability class:


if user.admin can :manage, :all elsif user.lab_admin can :manage, Project, :user => { :cost_center => user.cost_center} (????)


Lab_admin can manage all projects that belongs_to users that have same cost_center as lab_admin. Project doesn't have cost_center attribute. It has: Name User ... ...

Basically, I need:

  1. from user.cost_center, get the all user.id that has the same cost_center
  2. from user.id, get Project.user_id
  3. display

I did lots of search and cannot find a solution to this. How do I define this condition in ability?

Thanks,

graywh commented 11 years ago

I think what you have will work fine. When searching for projects accessible by a lab_admin user, it will use an inner join with users and a where condition on users.cost_center.

zhaohuic commented 11 years ago

Thanks. But now I got the error as:

NoMethodError in ProjectsController#index

undefined method `class_name' for nil:NilClass

Which 'class_name' does it refer to? The problem is that project doesn't have cost_center attr.

xhoy commented 10 years ago

Dear submitter, Since cancan/raynB hasn't been active for more than 6 months and no body else then ryam himself has commit permissions the cancan project is on a stand still. Since cancan has several issues including missing support for rails 4 cancan is moving forward to cancancan. More details on: #994

If your feel that your pull request or bug is still applicable (and hasn't been merged in to cancan) it would be really appreciated if you would resubmit it to cancancan (https://github.com/cancancommunity/cancancan)

We hope to see you on the other side!