LoginSignup
11
11

More than 5 years have passed since last update.

【rails】初期データにseed_fuで画像を入れたいときの解決法

Last updated at Posted at 2016-04-28

seed_fu実行時に画像を入れたいときってありますよね
そんなときにはこんな感じに書いてます

①まず入れたい画像をdb/fixtures/imagesディレクトリあたりに用意する

スクリーンショット 2016-04-28 18.35.56.png

まあぶっちゃけ場所はどこでもいい笑

②作成したいシードデータを作成する

Rails.root.joinを使用してして、さっき用意した画像のあるフォルダを指定し、openする

db/fixtures/development/image.rb
Image.seed do |s|
  s.id = 1
  s.content = Rails.root.join("db/fixtures/images/photo1.jpg").open
end

Image.seed do |s|
  s.id = 2
  s.content = Rails.root.join("db/fixtures/images/photo2.jpg").open
end

...

これだけ!簡単!

ただこのままだとえんえんと新しい画像が作り続けられてしまうので

③保存先のディレクトリのなか見を毎回削除する

db/fixtures/development/image.rb

# 前回のシード画像を削除
require 'fileutils'
Dir.chdir 'public/uploads/photos/' #僕はここに保存しているだけなので適宜変更
FileUtils.rm(Dir.glob('*.*'))

Image.seed do |s|
  s.id = 1
  s.content = Rails.root.join("db/fixtures/images/photo1.jpg").open
end

Image.seed do |s|
  s.id = 2
  s.content = Rails.root.join("db/fixtures/images/photo2.jpg").open
end

...

 完成や!

参考URL

Ruby:ディレクトリ内のファイルの削除
http://fuwakukara.seesaa.net/article/376399708.html

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