CanCan: How to define ability with some conditions

46 views
Skip to first unread message

Роман Ярыгин

unread,
Feb 16, 2014, 11:57:33 PM2/16/14
to rubyonra...@googlegroups.com
Hello everyone!

I have code:

if user.role == "topmanager"
        can :read, ActiveAdmin::Page, :name => "Dashboard" 
        can :manage, Realty, agent: {agency_id: user.agency_id}
...

And I want to add another condition, can :manage, Realty, agent: nil
How to do it? Defining it two times gets error: 

undefined method `reflect_on_association' for Class:Class


How can I define multiple conditions for one ability?

Martin Streicher

unread,
Feb 17, 2014, 9:53:00 AM2/17/14
to rubyonra...@googlegroups.com
So you want to say "The user can manage Realty if the agent has the right agency ID or if the agent is nil"?

If so, don't use the hash version of the condition. Go ahead and spell it out. 

You could also try agent: {agency_id: [nil, user.agency_id] )


James Davis, PhD

unread,
Feb 17, 2014, 11:08:27 AM2/17/14
to rubyonra...@googlegroups.com
You can use the 'or' & 'and' operators in the ability class.

can :manage, Realty do |realty|
    realty.new_record? or
    realty.agency_id == nil or
    realty.agency.agents.include?(user)
 end 
Reply all
Reply to author
Forward
Message has been deleted
0 new messages