rails cancancan cancan has_many through abilities

Marsel.V

company.rb :

class Company < ActiveRecord::Base
  has_many :companies_admins, dependent: :destroy
  has_many :supervisors, through: :companies_admins
end

companies_admin.rb :

class CompaniesAdmin < ActiveRecord::Base
    belongs_to :company
    belongs_to :supervisor, foreign_key: "admin_id"
end

supervisor.rb :

class Supervisor < Admin
    has_many :companies_admins, foreign_key: "admin_id"
    has_many :companies, through: :companies_admins, foreign_key: "admin_id"
end

나는 cancancan gem을 사용합니다. 내 ability.rb :

    class Ability
      include CanCan::Ability

      def initialize(user)
        user ||= Admin.new # guest user (not logged in)
        if user.type == "Administrator"
            can :manage, :all
        elsif user.type == "Supervisor"
            can :manage, Company, companies_admins: {supervisor: { :id => user.id } }
        end
  end
end

companies_controller.rb :

class CompaniesController < ApplicationController
    load_and_authorize_resource only: [:new, :create, :edit, :update, :index, :show, :destroy]
    load_and_authorize_resource :supervisor
    load_and_authorize_resource through: :supervisor
...
end

관리 할 수 ​​있고 관계가있는 회사 만 감독해야합니다. 예 : 감독자

companies_admins

회사 id = 10 페이지를 열면 액세스가 거부됩니다.

Started GET "/companies/10" for 127.0.0.1 at 2016-06-05 14:23:01 +0300
Processing by CompaniesController#show as HTML
  Parameters: {"id"=>"10"}
  Company Load (0.4ms)  SELECT  "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1  [["id", 10]]
  Admin Load (0.3ms)  SELECT  "admins".* FROM "admins" WHERE "admins"."id" = $1 LIMIT 1  [["id", 4]]
  CompaniesAdmin Load (0.4ms)  SELECT "companies_admins".* FROM "companies_admins" WHERE "companies_admins"."company_id" = $1  [["company_id", 10]]
  Supervisor Load (0.4ms)  SELECT  "admins".* FROM "admins" WHERE "admins"."type" IN ('Supervisor') AND "admins"."id" = $1 LIMIT 1  [["id", 2]]
  Supervisor Load (0.4ms)  SELECT  "admins".* FROM "admins" WHERE "admins"."type" IN ('Supervisor') AND "admins"."id" = $1 LIMIT 1  [["id", 4]]
Redirected to http://localhost:3000/
Completed 302 Found in 20ms (ActiveRecord: 1.9ms)

그 이유는 무엇입니까? 표현 "포함"을 식별하는 방법?

편집 : 매우 이상합니다. 관리자라도 : all Company를 교체 할 때 액세스가 거부되었습니다. 왜?

def initialize(user)
    user ||= Admin.new # guest user (not logged in)
    puts user.type
    if user.type == "Administrator"
        can :manage, Company
    elsif user.type == "Supervisor"
        can :show, :all 
    end
end

Started GET "/companies/10" for 127.0.0.1 at 2016-06-05 22:55:49 +0300
Processing by CompaniesController#show as HTML
  Parameters: {"id"=>"10"}
  Admin Load (0.3ms)  SELECT  "admins".* FROM "admins" WHERE "admins"."id" = $1 LIMIT 1  [["id", 1]]
Administrator
Redirected to http://localhost:3000/
Completed 302 Found in 42ms (ActiveRecord: 2.5ms)

레일 콘솔에서 :

irb(main):005:0> mi = Admin.find(1)
  Admin Load (0.7ms)  SELECT  "admins".* FROM "admins" WHERE "admins"."id" = $1 LIMIT 1  [["id", 1]]
=> #<Administrator id: 1, type: "Administrator", login: "mars", crypted_password: "8d6ff3f5b32b22726a45b1f8fa69519debf9ec8157d78f8e41...", password_salt: "2oMqwXKIukbKpdEXip", persistence_token: "37127e1f262d4efb44bc458df76e110a6ee78969c94c84a43c...", created_at: "2016-06-04 21:11:18", updated_at: "2016-06-05 09:06:15">
irb(main):006:0> comp = Company.find(10)
  Company Load (0.9ms)  SELECT  "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1  [["id", 10]]
=> #<Company id: 10, parent_id: nil, address_id: 6, name: "test_address"...>
irb(main):007:0> ability = Ability.new(mi)
Administrator
=> #<Ability:0x007f09513a0938 @rules=[#<CanCan::Rule:0x007f09513a0898 @match_all=false, @base_behavior=true, @actions=[:manage], @subjects=[Company(id: integer, parent_id: integer, address_id: integer, name: string, info: string, created_at: datetime, updated_at: datetime, site_link: string, vk_link: string, raiting: float, city_id: integer, paid: integer)], @conditions={}, @block=nil>], @rules_index={Company(id: integer, parent_id: integer, address_id: integer, name: string, info: string, created_at: datetime, updated_at: datetime, site_link: string, vk_link: string, raiting: float, city_id: integer, paid: integer)=>[0]}>
irb(main):008:0> ability.can?(:manage, comp)
=> true

내가 뭘 잘못 했어?

Marsel.V

흠, 작동합니다.

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= Admin.new # guest user (not logged in)
    if user.type == "Administrator"
        can :manage, Company
    elsif user.type == "Supervisor"
        can :manage, Company do |comp|
            comp.supervisor_ids.include?(user.id)
        end
    end
  end
end

companies_controller.rb :

class CompaniesController < ApplicationController
    load_and_authorize_resource only: [:new, :create, :edit, :update, :index, :show, :destroy]
....

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Rails has_many : through with the where 절

분류에서Dev

has_many / : through rails4

분류에서Dev

Rails has_many : through, undefined method

분류에서Dev

Rails 3: has_many through controller action

분류에서Dev

ActiveRecord, Rails 4 : has_many : through with scoped conditions failure

분류에서Dev

Ruby on Rails has_many : through in a polymorphic association

분류에서Dev

ordering through an has_many relationship with a condition in rails 3 / active records / postgresql

분류에서Dev

ActiveRecord has_many through inverse_of causing rails admin to work?

분류에서Dev

Rails 4 활성 레코드 모델 has_many through associations?

분류에서Dev

has_many : through in Rails로 생성 및 업데이트

분류에서Dev

Rails 4 : : has_many, : through 및 테이블 이름

분류에서Dev

Ruby on Rails 'has_many : through', 데이터 저장

분류에서Dev

Rails 자체 참조 has_many through : is not added the right record

분류에서Dev

Rails 5.1 has_many through-관련 필드

분류에서Dev

How do I check CanCan abilities on an object in a `shared/partial`?

분류에서Dev

has_many 후 has_many : through?

분류에서Dev

Rails 5-CanCan

분류에서Dev

Ruby on Rails CanCan Gem

분류에서Dev

Rails는 has_many : through 관계에서 데이터를 생성합니다.

분류에서Dev

has_many : through 관계에서 Rails NameError 초기화되지 않은 상수

분류에서Dev

has_many : through 관계에서 Rails NameError 초기화되지 않은 상수

분류에서Dev

has_many through : in Rails를 사용하여 현재 및 이전 관계 쿼리

분류에서Dev

중첩 된 속성에 대한 양식 도우미 has_many through in rails 4

분류에서Dev

Rails는`has_many : through` 텍스트 필드를 통해 검색합니다.

분류에서Dev

Rails has_many : through "오류-products.category 열이 존재하지 않습니다"

분류에서Dev

has_many, through, class_name 및 where 절이있는 Rails 모델 연결

분류에서Dev

link to relationship name in has_many :through

분류에서Dev

has_many : through 양식

분류에서Dev

Finding Users with has_many :through

Related 관련 기사

  1. 1

    Rails has_many : through with the where 절

  2. 2

    has_many / : through rails4

  3. 3

    Rails has_many : through, undefined method

  4. 4

    Rails 3: has_many through controller action

  5. 5

    ActiveRecord, Rails 4 : has_many : through with scoped conditions failure

  6. 6

    Ruby on Rails has_many : through in a polymorphic association

  7. 7

    ordering through an has_many relationship with a condition in rails 3 / active records / postgresql

  8. 8

    ActiveRecord has_many through inverse_of causing rails admin to work?

  9. 9

    Rails 4 활성 레코드 모델 has_many through associations?

  10. 10

    has_many : through in Rails로 생성 및 업데이트

  11. 11

    Rails 4 : : has_many, : through 및 테이블 이름

  12. 12

    Ruby on Rails 'has_many : through', 데이터 저장

  13. 13

    Rails 자체 참조 has_many through : is not added the right record

  14. 14

    Rails 5.1 has_many through-관련 필드

  15. 15

    How do I check CanCan abilities on an object in a `shared/partial`?

  16. 16

    has_many 후 has_many : through?

  17. 17

    Rails 5-CanCan

  18. 18

    Ruby on Rails CanCan Gem

  19. 19

    Rails는 has_many : through 관계에서 데이터를 생성합니다.

  20. 20

    has_many : through 관계에서 Rails NameError 초기화되지 않은 상수

  21. 21

    has_many : through 관계에서 Rails NameError 초기화되지 않은 상수

  22. 22

    has_many through : in Rails를 사용하여 현재 및 이전 관계 쿼리

  23. 23

    중첩 된 속성에 대한 양식 도우미 has_many through in rails 4

  24. 24

    Rails는`has_many : through` 텍스트 필드를 통해 검색합니다.

  25. 25

    Rails has_many : through "오류-products.category 열이 존재하지 않습니다"

  26. 26

    has_many, through, class_name 및 where 절이있는 Rails 모델 연결

  27. 27

    link to relationship name in has_many :through

  28. 28

    has_many : through 양식

  29. 29

    Finding Users with has_many :through

뜨겁다태그

보관