简体   繁体   English

Ruby on Rails-CanCan可以通过很多对很多宝石

[英]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. 在Rails 4上。我很难理解如何授权用户能够通过CanCan编辑组织的信息。

Use Case 1: Users have many organizations; 用例1:用户有很多组织; organizations have many users. 组织有很多用户。 This relationship information is stored in the third model, UserOrganization (with :user_id and :organization_id attributes). 此关系信息存储在第三个模型UserOrganization中(具有:user_id:organization_id属性)。 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): 我了解了这段代码,但是不起作用(在capability.rb中):

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

(says undefined method user_id) (表示未定义的方法user_id)

Use Case 2: There is a fourth model, OrganizationDetails. 用例2:第四个模型是OrganizationDetails。 One organization can have many organization_details. 一个组织可以有多个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. 换句话说,用户->有很多-> UserOrganizations->属于->组织->有很多-> 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. 如何在CanCan中格式化此格式,以便用户可以创建/编辑通过UserOrganization模型链接到的组织详细信息。 Thanks. 谢谢。 All controllers have load_and_authorize_resource and the appropriate has_many and belongs_to code in the models. 所有控制器在模型中都有load_and_authorize_resource以及适当的has_manybelongs_to代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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