简体   繁体   中英

Ruby on Rails - CanCan Gem with Many to Many Through

On Rails 4. I'm having trouble understanding how to authorize users to be able to edit their organization's information through CanCan.

Use Case 1: Users have many organizations; organizations have many users. This relationship information is stored in the third model, UserOrganization (with :user_id and :organization_id attributes). So basically, users are able to edit org info as long as they are linked through that third model. I learned about this piece of code but it does not work (in ability.rb):

def initialize(user)
  can [:show, :edit, :update], Organization, user_organizations: { user_id: user.id }
end

(says undefined method user_id)

Use Case 2: There is a fourth model, OrganizationDetails. One organization can have many organization_details. I would also like the user to be able to edit his/her organization's details.

In other words, Users -> has many -> UserOrganizations -> belongs to -> Organizations -> has many -> OrganizationDetails.

How do I format this in CanCan so a user can create/edit those org details he/she is linked to through the UserOrganization model. Thanks. All controllers have load_and_authorize_resource and the appropriate has_many and belongs_to code in the models.

Figured out how to do this.

To restrict by Organization:

can [:show, :edit, :update], Organization do |organization|
  UserOrganization.where(user_id: user.id, organization_id: organization.id).any?
end

To restrict by OrganizationDetail

can [:show, :edit, :update], OrganizationDetail do |organization_detail|
  UserOrganization.where(user_id: user.id, organization_id: organization_detail.organization.id).any?
end

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