1

Devise と Cancan を使用して、Rails アプリでアクセス許可を作成しようとしています。

アビリティ.rb:

class Ability
    include CanCan::Ability

    def initialize(user)
        if user.role ==  'admin'
            can :manage, :all
        else
            can :read, :all
        end
    end
end

user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :role
  # attr_accessible :title, :body


  def role(role)
    roles.include? role.to_s
  end

end

見る

            <% if can? :update, review %>
                <p><p><i><a href = '/products/<%= @product.id %>/reviews/<%= review.id %>/edit'>Edit</a>
            <% end %>

ビューのこの行の nil:NilClass に対して未定義のメソッド `role' というエラーが表示されます。これを修正する方法について何かアドバイスはありますか? https://github.com/ryanb/cancan/wiki/Role-Based-Authorizationをガイドとして
使用しようとしています

4

2 に答える 2

0

追加してみてください

user ||= User.new # guest user (not logged in)

それがあなたの役割のエラーを修正するかどうかを確認します。

class Ability
    include CanCan::Ability

    user ||= User.new # guest user (not logged in)

    def initialize(user)
        if user.role ==  'admin'
            can :manage, :all
        else
            can :read, :all
        end
    end
end

そうすれば、ユーザーがゼロであることを除外できます。

于 2013-05-20T22:48:30.733 に答える