1

私は一日中cancanを機能させようとしています。さまざまなチュートリアルを使用して何度かやり直しましたが、同じエラーが発生し続けます。

それは非常に簡単です。私は、管理者またはユーザーのいずれかの役割を持つことができるユーザー アカウント (Devise で作成) を持っています。能力クラスは次のとおりです。

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.role? :admin
      can :manage, :all
    end
  end
end

プロファイル コントローラにはload_and_authorize_resource、クラス User に含まれるという行がありますROLES = %w[admin user]。に行くとhttp://localhost:3000/profiles/エラーが表示されます

wrong number of arguments (2 for 1)app/models/ability.rb:6:in初期化中'`

別の方法user.admin?を使用すると、

undefined method `admin?' for #<User:0x5b34c10>

上記のエラーをグーグルで検索すると多くの結果が得られるため、この問題を抱えているのは私だけではありませんが、解決策はどれもうまくいきませんでした.

はい、ロール列をユーザーテーブルに追加しました

class AddRoleToUsers < ActiveRecord::Migration
  def change
    add_column :users, :role, :string
  end
end

Gem を追加し、bundle install を実行して、サーバーを再起動しました。

4

1 に答える 1

0

次のものがある場合、これは機能するはずです。

アビリティ.rb

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new # guest user
   # raise user.role?(:administrator).inspect
    if user.role? :administrator

      can :manage, :all
      can :manage, User

    elsif user.role? :user
      can :read, :all

    end

  end
end

RoleUser.rb

class RoleUser < ActiveRecord::Base
  # attr_accessible :title, :body
  belongs_to :user
  belongs_to :role

end

役割

class Role < ActiveRecord::Base
  attr_accessible :name

  has_and_belongs_to_many :users
end

ユーザー.rb

 class User < ActiveRecord::Base

 has_and_belongs_to_many :roles

  def role?(role)
    self.roles.find_by_name(role.to_s.camelize)
  end

これは、ロールを定義して検索し、ロールを文字列に変換してラクダ化するときに必要です。

種.rb

%w(Employee Administrator).each { |role| Role.create!(:name => role)}

配列Userとを作成しAdministratorます。

これらの手順を正しく実行すれば、これは機能するはずです。また、次の移行があることも確認してください。

class UsersHaveAndBelongsToManyRoles < ActiveRecord::Migration
  def self.up
    create_table :roles_users, :id => false do |t|
      t.references :role, :user
    end
  end

  def self.down
    drop_table :roles_users
  end
end

次に、あなたの見解では、次のcan?ようにしてを使用する必要があります

<% if can? :manage, User %> 
  .......
    ....
  ...
<% end %> 
于 2013-02-26T06:19:56.300 に答える