Inserting default "admin" user into database during Rails App startup

Posted by gbc on Stack Overflow See other posts from Stack Overflow or by gbc
Published on 2010-05-05T00:51:28Z Indexed on 2010/05/05 0:58 UTC
Read the original article Hit count: 212

Filed under:

I'm building my first real rails application for a little in-house task. Most of the application tasks require authentication/authorization. The first time the app starts up (or starts with a wiped db), I'd like the process to be:

  1. User logs into the admin panel using "admin" & "admin" for authentication info.

  2. User navigates to admin credentials editing page and changes name and password to something safer so that "admin" & "admin" is no longer a valid login.

To achieve this result, I'd like to stuff a default username & password combination into the database on if the application starts up and detects that there are no user credentials in the 'users' table. For example:

if User.count == 0
  User.create(:name => "admin", :password => "admin")
end

However, I'm unsure where to place that code. I tried adding an initializer script in the config/initializers, but the error I received appeared to indicate that the model classes weren't yet loaded into the application. So I'm curious to know at what point I can hook into the application startup cycle and insert data into the database through ActiveRecord before requests are dispatched.

© Stack Overflow or respective owner

Related posts about ruby-on-rails