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

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.

Run a rake db:seed multiple times without creating duplicate records?

Use a validation. If you don't want duplicate records, validate the uniqueness of one or more fields. In you town_health_record.rb

class TownHealthRecord
validates_uniqueness_of :city
validates uniqueness_of :health, scope: :person # If you wanted to validate a combination of fields
end

On an added side not, .create! will raise errors. .create will not. Same goes for save! and .update_attributes!.

Avoid duplicate records created via seeds.rb?

Try this :

 Post.where( title: "Unique Title!",  body: "this is the most amazingly unique post body ever!").first_or_create

Hope this will help you.

rake db:seed doesn't do anything

You can use find_or_create_by!(attributes, &block) which is like find_or_create_by, but calls create! so an exception is raised if the created record is invalid. APIDock

What happens when you run rake:db seed twice?

It will duplicate.

If you want to run multiple times, but prevent duplication. I guess you could:

  1. Use validation in one key field like putting validate_uniqueness_of :key_attribute
  2. Test the count of your table like:

    MyClass.create if MyClass.count == 0

  3. Better solution might be to use find_or_create_by method. See the docs: http://easyactiverecord.com/blog/2014/03/24/using-find-or-create-with-multiple-attributes/

How can I seed only my test-database without specifying additional arguments?

In your seed_fu task you can set the environment explicitly:

Rails.env = 'test'

To accomplish what you need, I'd wrap the seed_fu task like this:

namespace :db do
task :custom_seed => :environment do
Rails.env = 'test'
Rake::Task["db:seed_fu"].execute
end
end

Then just call:

rake db:custom_seed


Related Topics



Leave a reply



Submit