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

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


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 => "me@gmail.com")

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.


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.


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)  endend

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.