將 Rails 環境帶入 rake 裡,讓 rake 可以使用 Rails 的元素,像是 Model:
1 2 3 4 5 6 7
| namespace :user do desc "建立使用者" task :init => :environment do User.create(email: Faker::Internet.email ,password: '123456') puts "user created" end end
|
如果沒有導入環境給 rake ,rake 就找不到 User ,就沒辦法 new 了。
終端機輸入:
透過回圈,一個指令,產生多筆資料:
1 2 3 4 5 6 7 8 9
| namespace :user do desc "建立使用者" task :init => :environment do 5.times { user = User.create(email: Faker::Internet.email ,password: '123456') puts "user: #{user.email} created!" } end end
|
更複雜的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| namespace :blog do desc "建立初始資料" task :init => :environment do 5.times { u = User.create(email: Faker::Internet.email, password: "123456") blog = u.create_blog( handler: Faker::Name.unique.name.downcase.gsub(" ", "_").delete("."), title: Faker::Lorem.sentence, description: Faker::Lorem.paragraphs(number: 2).join ) puts "blog #{blog.handler} created" 10.times { article = u.articles.create( title: Faker::Lorem.sentence, content: Faker::Lorem.paragraphs(number: 5).join ) puts " title: #{article.title} created" } puts "user: #{u.email} created!" } end end
|