Skip to content
This repository

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

zhaohuic opened this Issue · 3 comments

3 participants

zhaohuic Will Gray xhoy

My two associations:

class Project < ActiveRecord::Base
belongs_to :user

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

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 that has the same cost_center
2. from, 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?


Will Gray

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.


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

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 (

We hope to see you on the other side!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.