开发者

Can I use cancan with many resources?

开发者 https://www.devze.com 2023-02-14 12:07 出处:网络
I use devise and created two models, Doctor and Patient. When I write load_and_authorize_resource cancan gives an exception

I use devise and created two models, Doctor and Patient. When I write load_and_authorize_resource cancan gives an exception

undefined local variable or method `current_user

How c开发者_开发百科an I use cancan for both of them?


There is a method called current_ability in the Application Controller, you can simply overwrite it.

Changing current_ability documentation

It will look something like this

def current_ability
  @current_ability ||= Ability.new(current_user)
end

But you may change it to

def current_ability
  if current_doctor
    @current_ability ||= Ability.new(current_doctor)
  else
    @current_ability ||= Ability.new(current_patient)
  end
end

That will allow the initialize method in the app/models/ability.rb to recieve either the current_patient or the current_doctor depending on the case. You could customize it to look something like this

class Ability
  include CanCan::Ability

  def initialize(resource)
    if resource.class == Patient
      can, Read Something
      can, Edit Other
      .
      .
      .
    else
      can, Read Something
      can, Edit Other
      .
      .
      .
    end
      .
      .
      .

I hope this help, you can also see the cancan Full doc


You can find a complete configuration of Devise and Cancan here: Part 1 Part 2

0

精彩评论

暂无评论...
验证码 换一张
取 消