LoginSignup
31
26

More than 5 years have passed since last update.

rake db:seedを使ったデータの投入

Last updated at Posted at 2016-05-25

個別のデータの呼び込み

データを追加するテーブルに対応したモデルのクラスを用意します
クラスで用意されているcreateメソッドを使ってデータを追加していきます

~1行ずつ書く場合~

seeds.rb
Model.create(name: "Railsの基礎知識", position: 1)
Model.create(name: "Rubyの基礎知識", position: 2)

~まとめて記述する場合~

seeds.rb
5.times do |i|
     Page.create(name: "テスト #{i}", model_id: 1)
end
Gemfileなどがまとまっているディレクトリで
$rake db:seed

これで記述したコードが実装されてテーブルにデータが追加されます!

RubyだとCSVデータも読み込めるらしいですね

seeds.rb
require "csv"

CSV.foreach('db/sample.csv') do |row|
  Model.create(name: row[0], sales_date: row[1], price: row[2])
end
31
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
26