2

ライアンベイツのビデオチュートリアルに従って、レールでデバイスを使用して学習しています

それは私にとってはうまくいきます。

しかし、cancan統合でロールベースの条件を適用するには、アプリケーションにロールを追加する必要があります

私のモデル1:user.rb

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_and_belongs_to_many :roles

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

私のモデル2:role.rb

class Role < ActiveRecord::Base
  attr_accessible :name
  has_and_belongs_to_many :users
end

私のユーザー移行ファイル

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, :default => 0
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      t.timestamps
    end

    add_index :users, :email,                :unique => true
    add_index :users, :reset_password_token, :unique => true
  end
end

私の役割移行ファイル

class CreateRoles < ActiveRecord::Migration
  def change
    create_table :roles do |t|
      t.string :name

      t.timestamps
    end
  end
end

私の結合テーブル移行ファイル

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

  def down
    drop_table :roles_users
  end
end

ユーザーを作成するときに、ロールをユーザーに関連付け、結合テーブルにエントリが必要です。

どうすればできますか??

4

1 に答える 1

3

Rails は結合テーブル エントリを自動的に作成します。さまざまな方法でユーザーにロールを設定できます。ここではいくつかの例を示します。

 @user << Role.find_by_name('admin') # Adds the admin role to the users roles and save
 @user.roles.create(:name => 'admin') # Creates a new role and add to the the user
 @user.role_ids = [1,2,3] # Adds the roles with id 1, 2 and 3 and delete all others
 @user.roles = [Role.find_by_name('admin'), Role.find_by_name('superuser')] # Adds admin and superuser roles and delete all others

ここで利用可能なすべてのオプションを確認できます: http://guides.rubyonrails.org/association_basics.html#has_and_belongs_to_many-association-reference

これは、新しいユーザーを作成するときにデフォルトの役割が必要な場合は、次のようにできることを意味します。

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
  before_create :set_default_role

  private
  def set_default_role
    # Add the default role if no roles is set
    self.roles << Role.find_by_name('default') if roles.empty?
  end
end

この件について詳しくは、http: //www.tonyamoyal.com/2010/07/28/rails-authentication-with-devise-and-cancan-customizing-devise-controllers/をご覧ください。

于 2013-06-20T07:48:46.203 に答える