Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending to rake db:seed in rails and running it without duplicating data

Rake db:seed populates your db with default database values for an app right? So what if you already have a seed and you need to add to it(you add a new feature that requires the seed). In my experience, when I ran rake db:seed again, it added the existing content already so existing content became double.

What I need is to add some seeds and when ran, it should just add the newest ones, and ignore the existing seeds. How do I go about with this? (the dirty, noob way I usually do it is to truncate my whole db then run seed again, but that's not very smart to do in production, right?)

like image 874
corroded Avatar asked Aug 13 '10 12:08

corroded


3 Answers

A cleaner way to do this is by using find_or_create_by, as follows:

User.find_or_create_by_username_and_role(
  :username => "admin",
  :role => "admin",
  :email => "[email protected]")

Here are the possible outcomes:

  1. A record exists with username "admin" and role "admin". This record will NOT be updated with the new e-mail if it already exists, but it will also NOT be doubled.
  2. A record does not exist with username "admin" and role "admin". The above record will be created.
  3. Note that if only one of the username/role criteria are satisfied, it will create the above record. Use the right criteria to ensure you aren't duplicating something you want to remain unique.
like image 75
sscirrus Avatar answered Oct 15 '22 18:10

sscirrus


I do something like this.... When I need to add a user

in seeds.rb:

if User.count == 0
  puts "Creating admin user"
  User.create(:role=>:admin, :username=>'blagh', :etc=>:etc)
end

You can get more interesting than that, but in this case, you could run it over again as needed.

like image 22
Jesse Wolgamott Avatar answered Oct 15 '22 17:10

Jesse Wolgamott


Another option that might have a slight performance benefit:

# This example assumes that a role consists of just an id and a title.

roles = ['Admin', 'User', 'Other']
existing_roles = Role.all.map { |r| r.title }

roles.each do |role|
  unless existing_roles.include?(role)
    Role.create!(title: role)
  end
end

I think that doing it this way, you only have to do one db call to get an array of what exists, then you only need to call again if something isn't there and needs to be created.

like image 8
Lexun Avatar answered Oct 15 '22 18:10

Lexun