Search code examples
ruby-on-railsrubydeviseadmin

Trying to create an Admin user in devise, but I am getting an error


I have already set devise up and created a user model, and now I am trying to set up an admin without any luck. First I followed the steps in devise's documentation:

$ rails generate devise Admin

Updated my admin model to:

class Admin < ActiveRecord::Base
 devise :database_authenticatable, :registrable, :trackable, :timeoutable, :lockable  
end

Then I updated my migration to:

class DeviseCreateAdmins < ActiveRecord::Migration
  def self.up
    create_table(:admins) do |t|
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""
      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.integer  :failed_attempts, :default => 0 # Only if lock strategy is      :failed_attempts
      t.string   :unlock_token # Only if unlock strategy is :email or :both
      t.datetime :locked_at
      t.timestamps
    end
  end

  def self.down
    drop_table :admins
  end
end

then I go to /admins/sign_up and I get this error:

NoMethodError in Devise::Registrations#new
undefined method `title' for #<Admin:0x00000005fb17b0>
<%= f.text_field :title, autofocus: true %>

Does the title actually have to be defined,or is something else causing this? Is there a better way to create a single admin account in devise?


Solution

  • You did not create the title column for your Admin model (admins table) - thus exception.

    You should read about adding columns to table in Rails.

    To resolve this specific issue create new migration:

    rails g migration add_title_to_admins
    

    In generated file:

    add_column :admins, :title, :string
    

    Run the migration:

    rake db:migrate
    

    Now your admins will have title. To add new attributes (columns in db) follow the instructions as for title.