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:
- Use validation in one key field like putting
validate_uniqueness_of :key_attribute
Test the count of your table like:
MyClass.create if MyClass.count == 0
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
Nokogiri Error When Running Bundle Install
Singleton Method VS. Class Method
How to Update a Single Attribute Without Touching the Updated_At Attribute
Is Alias_Method_Chain Synonymous with Alias_Method
Refactoring a Large Routes.Rb File in Rails 4
Rails - Displaying Foreign Key References in a Form
Error Running 'Requirements_Osx_Brew_Libs_Install...' on MAC 10.7
Select Mailbox "Sent Mail" or "All Mail" in Ruby Net::Imap
How to Use Ruby " Case ... When " with Inequalities
Pg Error Could Not Connect to Server: Connection Refused Is the Server Running on Port 5432
Routing Error - Uninitialized Constant
Rails 3 Joins -- Select Only Certain Columns
Creating a Hash with Values as Arrays and Default Value as Empty Array
Open and Save Base64 Encoded Image Data Uri in Ruby