A simple way to seed a database in Rails
Creating default data into the database is very important before you write tests for backend, it’s called seeding.
I am going to share the way I did to add initial content after the database was created.
You can create seed data inside of db/seed.rb file, this file contains all the record creation needed to seed the database with its default values.
I have two models, the Destination model the Comment model, the destination has many comments.
The first step, list all the table names and then call `.destroy_all`, prepend db/seed.rb file with it will clear out all your destinations and comments record.
The second step, define the array to store all the created projects
Instead of defining each record, for example
You might want dynamically generate the record you need:
And to create some comments under destination, each method will help you iterate over destinations, create the new comment with a destination_id attribute and set it to destination.id
The third step, load the data and run the command in your terminal
Last but not least, please go to the database administrator to view the table data, make sure you seed it successfully.
Here is a pgAdmin4 table data view since I am using Postgres SQL to store my application data.
And If you are using SQLite as your storage application, the DB browser for SQLite might be a good choice to view your table data.
How do I view data in pgAdmin 4
How do I view data in pgAdmin 4?
Similar to How to view data in pgAdmin III, how do I view data in pgAdmin 4? Like the other question, I can't believe…
How to use faker to generate seed data