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

More than 3 years have passed since last update.

seedで初期データを生成するコードで使ったメソッド

Posted at

はじめに

 先日、投稿した「初期データをseeds.rbに記述して、ゲストログイン機能のエラーを解決してみた」でseeds.rbに初期データを作成したときに使ったいくつかのメソッドについて、説明する。

基本の書き方

seeds.rb
モデル名.メソッド(カラム名: )

create!

基本は、これかと…
単純に、「作って!」というやつ。
同じidや一意性のバリデーションによってエラーになることもあるので、注意が必要。

first_or_create_by!

中学英語みたいだが、firstorとつくので、
「id=1が存在しなければ、作るよ!」みないな意味。
つまり、初期データを作成する、ターミナルでrails db:seedを行う前に、データが存在すると、seed.rbで作成したデータは保存されない。

find_or_create_by!

同じく中学英語みたい。
「テーブルになければ、作るよ!」みたいな意味。

おわりに

 idのカラムを指定することができるが、その後に、生成するidが、seeds.rbで指定したidからの連番になってしまう。
ex)id=100をseeds.rbで記述していると、その次に情報を保存すると、id=101になる。

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