LoginSignup
4
1

More than 5 years have passed since last update.

画像を`bin/rake db:seed`で登録する

Posted at

テーブル構成はこんな感じ

  create_table "posts", force: :cascade do |t|
    t.string   "title"
    t.binary   "image"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

今日やりたかったのは、一覧表示の確認をするために予め画像データを登録したかった。
seedでデータと一緒に登録できれば楽だなぁと思って頑張ってみた

for num in 1..10 do
  image_path = File.join(Rails.root, "test/sample.jpg")
  image = File.open(image_path, 'rb').read
  Post.create(title: "title#{num}", image: image)
end
  1. サンプルになる画像を適当な場所に置く
  2. File.openでファイルを開いて、rbモードで開く

bってのがバイナリモードって意味。いまいち分かってないけどbinary型に登録するんだから付けるんだろうって思ってる。
rは読み込みモードって意味。
readメソッドは一度に読み込んで標準出力するんだって

後は、bin/rake db:seedすれば登録できる

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