Within my ruby on rails application I have the seeds file, which contains data on the users such as:
User.create(:password => "jb", :password_confirmation => "jb", :role => 'admin', :first_name => "Joe", :last_name => "Bloggs", :house_no => "1", :street => "A Street", :town => "A Town", :postcode => "ABC1 2DE", :email => "anemail#anemailaddress.co.uk")
But when I run rake db:setup it removes all the users data that I have entered into the database through the application (which is fine and expected) but does not enter the users data from the seeds.
I'm not sure if this makes a difference but I recently did three consecutive scaffolds.
What am I doing wrong?
I think you are looking to do a rake db:seed. Here is a good explanation of the other db rake tasks Difference between rake db:migrate db:reset and db:schema:load
db:seed runs the db/seed.rb file
db:schema:load loads the schema into the current env's database
db:setup runs both db:schema:load and db:seed
Related
I'm using the gem 'acts_as_tenant' in a Rails 3 project.
I would like to seed new data every time a new Tenant is added - but only for the new Tenant.
Is there a way to pass a variable to rake db:seed?
Something like:
rake db:seed -tenant=5
Thanks for the help!
This worked:
$ TENANT=5 rake db:seed
In seed.rb:
statuscode = Statuscode.first_or_create(
:tenant_id => ENV['TENANT'],
:statuscode => 'Completed',
:closed => true
)
Is there any conventions of rails or a right way to create/manipulate a table that will contain just one row?
If not, what is the best way to do that?
I need a way to store configurations of the system.
Thanks.
Edited:
The rake db:seed command, basically execute whatever code you write in db/seeds.rb file of your application. Though can write any code in this file, by convention you should write code which populate your database with the basic data,
for example: when ever your deploy your application somewhere, and create a new database for it, you want that user with admin credential must be present there. So you will write the code which create that user in this file. Below is the sample code which will create a user and assign admin role to him.
puts "********Seeding Data Start************"
admin = User.create(:first_name => 'System', :last_name => 'Admin',
:email => 'systemadmin#sunpower.com', :password => 'sunpoweradmin',
:password_confirmation => 'sunpoweradmin', :source_system_id => 'systemadmin',
:source_system => 'LP',:entity_type => "Customer", :target_system => "OPENAM")
if admin.errors.blank?
puts "***User #{admin.first_name} #{admin.last_name} created ***"
admin.add_role :admin # add_role is method defined by rolify gem
puts "***admin role assigned to #{admin.first_name} #{admin.last_name}***"
else
puts "admin user failed to create due to below reasons:"
admin.errors.each do |x, y|
puts"#{x} #{y}" # x will be the field name and y will be the error on it
end
end
puts "********Seeding Data End************"
Now whenever you recreate your database, you just need to run below command to populate the database, with the basic data
$ rake db:seed RAILS_ENV=production
The correct order to setup database in production, with all the rake task available within db namespace is as below
$rake db:create RAILS_ENV=production
$rake db:migrate RAILS_ENV=production
$ rake db:seed RAILS_ENV=production
NOTE: You can replace the first two commands with $rake db:setup RAILS_ENV=production , it will run both create and migrate internally
OR
You could use the rails-settings-cached gem which is a fork of the rails-settings gem
Once setup, you'll be able to do things such as:
Setting.foo = 123
Setting.foo # returns 123
Hope this may help you or what you are looking for..
I have simple rails 2 composer app. I can rake migrate and seed the app locally fine and the admin user in the seed file is setup. However the db does not seed on Heroku. I get the following error (with trace when i run - heroku run rake db:setup --trace ):
** Execute db:abort_if_pending_migrations
ROLES
rake aborted!
can't convert nil into String
This is my code:
seed.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# Environment variables (ENV['...']) are set in the file config/application.yml.
# See http://railsapps.github.io/rails-environment-variables.html
puts 'ROLES'
YAML.load(ENV['ROLES']).each do |role|
Role.find_or_create_by_name({ :name => role }, :without_protection => true)
puts 'role: ' << role
end
puts 'DEFAULT USERS'
user = User.find_or_create_by_email :name => ENV['ADMIN_NAME'].dup, :email => ENV['ADMIN_EMAIL'].dup, :password => ENV['ADMIN_PASSWORD'].dup, :password_confirmation => ENV['ADMIN_PASSWORD'].dup
puts 'user: ' << user.name
user.add_role :admin
user.save!
application.yml
GMAIL_USERNAME: Your_Username
GMAIL_PASSWORD: Your_Password
ADMIN_NAME: First User
ADMIN_EMAIL: user#example.com
ADMIN_PASSWORD: changeme
ROLES: [admin, user]
I'm reasonably new to rails. The app did seed initially, but i've made some migrations and rolledback once.
Any help much appreciated.
if you trace role with a "db:reset --trace" and add "put role" like this :
YAML.load(ENV['ROLES']).each do |role|
puts role
You can see that the first role is admin, but after the rake db:reset put the message "uninitialized constant Role"
So the problem is not the ENV['ROLES'] !
The rake task itself:
desc "This task creates a new user"
task :create_user, [:email, :password] => :environment do |t, args|
trole = Role.find_by_name('translator')
User.create(
:email => args.email,
:password => args.password,
:password_confirmation => args.password,
:role_id => trole.id)
end
The call:
rake create_user[user#host.com,password]
The output:
rake aborted!
Don't know how to build task 'create_user'
I really got stuck. All the advices I've found, even here, on StackOverflow, either don't cover the situation with two parameters, or are outdated/not working. Please help!
The syntax you've written should work fine in bash, so I'm guessing you're using zsh?
If so, it can't parse the [] correctly and these need to be escaped.
Try using:
rake create_user\[user#host.com,password\]
instead.
I've been using the Authlogic rails plugin. Really all I am using it for is to have one admin user who can edit the site. It's not a site where people sign up accounts. I'm going to end up making the create user method restricted by an already logged in user, but of course, when I clear the DB I can't create a user, so I have to prepopulate it somehow. I tried just making a migration to put a dump of a user I created but that doesn't work and seems pretty hacky. What's the best way to handle this? It's tricky since the passwords get hashed, so I feel like I have to create one and then pull out the hashed entries...
Rails 2.3.4 adds a new feature to seed databases.
You can add in your seed in db/seed.rb file:
User.create(:username => "admin", :password => "notthis", :password_confirmation => "notthis", :email => "admin#example.com")
Then insert it with:
rake db:seed
for production or test
RAILS_ENV="production" rake db:seed
RAILS_ENV="test" rake db:seed
My favorite feature in 2.3.4 so far
If you are using >= Rails 2.3.4 the new features include a db/seeds.rb file. This is now the default file for seeding data.
In there you can simple use your models like User.create(:login=>"admin", :etc => :etc) to create your data.
With this approach rake db:setup will also seed the data as will rake db:seed if you already have the DB.
In older projects I've sometimes used a fixture (remeber to change the password straight away) with something like users.yml:
admin:
id: 1
email: admin#domain.com
login: admin
crypted_password: a4a4e4809f0a285e76bb6b35f97c9323e912adca
salt: 7e8455432de1ab5f3fE0e724b1e71500a29ab5ca
created_at: <%= Time.now.to_s :db %>
updated_at: <%= Time.now.to_s :db %>
rake db:fixtures:load FIXTURES=users
Or finally as the other guys have said you have the rake task option, hope that helps.
Most used approach is to have a rake task that is run after deployment to host with empty database.
Add a rake task:
# Add whatever fields you validate in user model
# for me only username and password
desc 'Add Admin: rake add_admin username=some_admin password=some_pass'
task :add_admin => :environment do
User.create!(:username=> ENV["username"], :password=> ENV["password"],:password_confirmation => ENV["password"])
end