1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】初期データの設定について

Posted at

記事概要

Ruby on Railsに初期データを設定する方法について、まとめる

前提

  • Ruby on Railsでアプリケーションを作成している

用語

seedファイル

あらかじめデータをファイルに用意することで、そのデータを簡単にデータベースへ投入できる

手順

  1. db/seeds.rbに、データ生成のコードを記述する
    seeds.rb
    Item.create(name: 'ペン', price: 100)
    Item.create(name: 'ペン2', price: 200)
    Item.create(name: 'ノート1', price: 400)
    Item.create(name: 'ノート2', price: 600)
    Item.create(name: 'ペンケース1', price: 800)
    Item.create(name: 'ペンケース', price: 1000)
    Item.create(name: '本1', price: 1500)
    Item.create(name: '本2', price: 2000)
    Item.create(name: 'メガネ1', price: 20000)
    Item.create(name: 'メガネ2', price: 35000)
    
  2. DB作成やマイグレーションを行っていない場合は、下記を実施する
    # DB生成
    % rails db:create
    
    # マイグレーション
    % rails db:migrate
    
  3. シード値をDBに登録する
    % rails db:seed
    
  4. テーブルにシード値が登録されていることを確認する

Ruby on Railsまとめ

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?