seed-fu is a syntax that already exists but you can update only the records you want to change, execute it on a file-by-file basis, and write it easily. It is a convenient gem with sugar.
gem 'seed-fu'
Also execute this.
$ bundle install
#Must-have directory
db/fixtures
#Create different data for each environment
db/fixtures/development
db/fixtures/production
01_category.rb
Category.seed do |c|
c.id = 1
c.name = 'HTML'
end
Category.seed do |c|
c.id = 2
c.name = 'CSS'
end
Category.seed do |c|
c.id = 3
c.name = 'Ruby'
end
$ rails db:seed_fu
Use seed_once if you don't want to update the data once it's created.
Category.seed_once do |s|
s.id = 1
s.name = 'HTML'
end
When creating a seed file, you can write as follows in addition to the above description.
Category.seed(:id,
{ id: 1, name: 'HTML' },
{ id: 2, name: 'CSS' },
{ id: 3, name: 'Ruby' },
)
db/fixtures/development/category.csv
1,HTML
2,CSS
3,Ruby
Write the process to read from CSV.
db/fixtures/development/01_category.rb
require 'csv'
csv = CSV.read('db/fixtures/development/category.csv')
csv.each do |category|
Category.seed do |s|
s.id = category[0] #Here id
s.name = category[1] #Here name
end
end
Finally execute the following command
$ rails db:seed_fu
Since the password is not set properly in seed_fu, use the default seed.
db/fixtures/development/00_user.rb
User.create!(id: 1, name: 'yuh', email: '[email protected]',
password: 'password', password_confirmation: 'password')
Recommended Posts