简体   繁体   中英

cancancan manage a relationship Rails

I am running into an issue with the cancancan gem for rails

gem 'cancancan', '~> 1.10'

I have four models: User, Company, Locations, Groups

User: Belongs to Company Company: Has many Locations Location: Belongs to company Group: Belongs to Location

In the abilities model I have this:

can :manage, Group, :location => {:id => user.company.locations.map{|l| l.id}}

When creating a new group I am denied (don't have access)

I am looking for the correct way to allow a User to create a group with one of the companies location id's (NOTE: Without cancancan on this all works and all ID's are related and so on).

To make sure I'm understanding your question completely...

You're looking for a way to limit a User's ability to manage Groups based on the locations of the Company that User belongs to?

Assuming I've got that correct, I would recommend using #pluck :

can :manage, Group, location_id: user.company.locations.pluck(:id)

This collects all the :id 's on a User's Company's Locations, and ensures a User can only manage Groups that have a :location_id contained within that collection.

Functionally, this is identical to what you've done, but is more efficient in two ways:

  1. It doesn't involve any unnecessary Ruby logic

  2. Using #pluck only queries the :id on a location, as opposed to the entire location and all its attributes

Generally speaking, whenever you're accessing your database in Rails, you're better off doing so entirely with ActiveRecord methods. This will help prevent you from wasting time querying for extra information you don't need, and eliminate the extra overhead of using Ruby to re-structure your data.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM