'How to add roles to rails app from console? Cancan, Devise

I can create user already, but how add roles dynamically? from console or with admin rules? Devise, CanCan. I am new at Rails, but if you will propose me some ideas or materials, i will be happy.

User model:

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

  has_and_belongs_to_many :roles

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

end

Ability class

class Ability
include CanCan::Ability

def initialize(user)
  # Define abilities for the passed in user here. For example:
  user ||= User.new # guest user (not logged in)
  if user.role? :admin
    can :manage, :all
  elsif user.role? :editor
    can :edit, :all
  else
    can :read, :all
  end
  end
end

Role model

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

Migrations

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :login
      t.string :full_name
      t.date   :birthday
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""
      t.string :address
      t.string :city
      t.string :state
      t.string :country
      t.string :zip
      ## Recoverable
      t.string   :reset_password_token
       t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

     ## Confirmable
     # t.string   :confirmation_token
     # t.datetime :confirmed_at
     # t.datetime :confirmation_sent_at
     # t.string   :unconfirmed_email # Only if using reconfirmable

     ## Lockable
      # t.integer  :failed_attempts, :default => 0, :null => false # Only if lock   strategy is :failed_attempts
     # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at
       ...
    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 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


Solution 1:[1]

you need a migration for creating roles table. after that

Role.create!(:name => 'admin')

in rails console

Solution 2:[2]

Role.create(name: "admin") in rails console try it it's work

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 arun15thmay
Solution 2 Haneen Khairi