ruby - rails devise undefined method username when I want to use it with cancancan -


i want achieve role based authorisation in rails. login use gem devise, works perfect. after including code of cancancan in tutorial error undefined method username , when remove username error undefined method email...

here code:

ability.rb (to manage user specific role can do)

    class ability    include cancan::ability    def initialize(user)        user ||= user.new       if user.role?(:admin)        can :manage, :all      elsif user.role?(:mitarbeiter)        can :manage, :documents        can :manage, :entries      end    end  end 

a part of user.rb

      roles = {0 => :admin, 1 => :mitarbeiter}    attr_reader :role :    def initialize(role_id = 0)     @role = roles.has_key?(role_id) ? roles[role_id] : roles[0]    end    def role?(role_name)     role == role_name   end 

a part of application_controller.rb

  protect_from_forgery with: :exception    check_authorization    rescue_from cancan::accessdenied |exception|     flash[:warning] = exception.message     redirect_to root_path   end    private    def current_user     user.new(session[:id])   end    helper_method :current_user 

i can't whats wrong... thought have set @user @role in user.rb doesn't helped

i suggest removing user#initialize method , attr_reader :role declaration , create own role method follows:

def role   @role ||= roles.has_key?(role_id) ? roles[role_id] : roles[0] end  def role?(role_name)   role == role_name end 

this way achieve intended, without overriding activerecord's user#initialize method.

above code assumes, role_id stored in database in role_id column.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -