如何在roles_users表中填充数据使用rails中的devise?

时间:2013-06-20 07:24:23

标签: ruby-on-rails ruby-on-rails-3 devise ruby-on-rails-3.2 has-and-belongs-to-many

我正在学习在ryan bates视频教程中使用rails中的设计

它适用于我。

但现在我需要在我的应用程序中添加角色,以便在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

现在当我创建用户时,我希望我的角色与用户相关联,并且连接表应该有条目,

我该怎么办?

1 个答案:

答案 0 :(得分: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/