314
314

Reputation: 51

Ruby on rails database: can you create records in your code

I wan to create admin user for my application. I want to have admin created at the same time when the application is created. Like I want a record admin to already be in the database at the very beginning. Is it possible to initialize administrator before actually creating the application, so that when I put the application on heroku and it goes to production mode, the admin is already there with the password and username I specified in my code?

Upvotes: 0

Views: 145

Answers (4)

Richard Peck
Richard Peck

Reputation: 76774

To add to @Sasidaran's answer, you'll definitely be looking at the seeds functionality of Rails:

#db/seeds.rb
Model.find_or_create_by param: "Value"
Model.find_or_create_by param: "Value2"

$ rake db:seed
$ heroku run rake db:seed

It's best to think of the seeds file as a batch file -- it just runs through the commands you send to the models etc, allowing you to include any data you need. You can be as complicated or simple as you need.

--

In your case, we don't know your password, or how it's created.

If you're using bcrypt-ruby, you'll want to do something like (has_secure_password):

#app/models/user.rb
class User < ActiveRecord::Base
  has_secure_password
end

#db/seeds.rb
User.crate name: 'david', password: 'mUc3m00RsqyRe', password_confirmation: 'mUc3m00RsqyRe' #-> true

$ rake db:seed
$ heroku run rake db:seed

Devise does things differently (I believe). I can update with information about it if you're using it.

Upvotes: 0

Sasidaran
Sasidaran

Reputation: 454

Yes it can be done, using seeds.rb. You can add the initial datas to be loaded in the application after the first deployment.

Your can write the first admin to be created in seeds.rb

db/seeds.rb

in local you can run as rake db:seed (to populate the initial datas)

If you are using the default PostgreSQL (of heroku), you can run as,

heroku pg:reset
heroku run rake db:seed

Upvotes: 1

Mark Swardstrom
Mark Swardstrom

Reputation: 18070

I'll do this sometimes - add a before_create to the user class. It can create admins based on whatever I need.

before_create :first_user_admin

def first_user_admin
  self.admin = true if User.count == 0
end

Upvotes: 0

sts
sts

Reputation: 380

You can use seeds.rb file inside rails to create records what you need and than heroku run rake db:seed on heroku

Upvotes: 0

Related Questions