LoginSignup
11
9

More than 5 years have passed since last update.

rake db:seedのようなことをPhoenixFrameworkでもやりたい!

Posted at

出来るさ、seed.exsならね。
というわけで、今回は初期データをDBに突っ込むことが出来るrake db:seedをPhoenixFrameworkでもやってみようとおもいます。

やり方

rake db:seedの時はdb/seeds.rbがありましたが、Phoenixにはprev/repo/seed.exsというファイルがあります。

seed.exs
# Script for populating the database. You can run it as:
#
#     mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
#     TestApi.Repo.insert!(%SomeModel{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.

ここに書かれているように、insert処理を書いてmix run priv/repo/seeds.exsを実行すれば初期データが突っ込まれます。

では、試しにTestApiプロジェクトにHogeモデルが存在すると仮定してinsert処理を書いてみましょう。

seed.exs
TestApi.Repo.insert!(%Hoge{
  name: "HOGE"
})

これでmix run priv/repo/seeds.exsを実行すればHogeモデルに対応したテーブルにデータが追加されます。

応用編

それでは一歩進んだやり方として、aliasを使いつつ多次元連想配列をinsertしましょう。

seed.exs
// エイリアス
alias TestApi.Hoge
alias TestApi.Repo

// 多次元連想配列
initial_hoges = [ 
    [   
        {:name, "Hoge"},
        {:info, "Programming Slang in Japanese."}
    ],  
    [   
        {:name, "Fuga"},
        {:info, "Programming Slang in Japanese."}
    ],  
    [   
        {:name, "Foo"},
        {:info, "Programming Slang in Foreign countries."}
    ],  
    [   
        {:name, "Bar"},
        {:info, "Programming Slang in Foreign countries."}
    ] 
]

// ループ処理
for initial_hoge <- initial_hoges do
    Repo.insert!(
        %Hoge{
            name: initial_hoge[:name],
            info: initial_hoge[:info]
        }   
    )   
end

このようにaliasを使えば簡潔に書くことが出来、多量のインサートデータがあったとしても多次元配列にすればループ処理で簡単にinsertさせることが出来ます。

まだ他にも色々な記述方法があると思いますので、色々と試してみてください。

11
9
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
11
9