LoginSignup
1
0

More than 1 year has passed since last update.

ActiveStorageを利用した際のseedデータ作成

Last updated at Posted at 2021-08-19

初投稿です!宜しくお願いします。

やりたいこと

ActiveStorageを使って投稿機能を実装している状態でseedデータを準備したい。
ファイルの添付を必須にするバリデーションをかけている場合のデータを作成したい。

seedデータの用意

以下のやり方場合は、
ActiveRecord::RecordInvalid: バリデーションに失敗しました: 写真を追加してください
となってしまった。

失敗例

db/seeds.rb
10.times do |n|
  post = Post.create!(
    user_id: "1",
    content: "投稿します!",
  )
  post.images.attach(
    io: File.open(Rails.root.join("./app/assets/images/post/test.jpeg")),
    filename: "test.jpeg"
  )
end

成功例

db/seeds.rb
10.times do |n|
  post = Post.new(
    user_id: "1",
    content: "投稿します!",
  )
  post.images.attach(
    io: File.open(Rails.root.join("./app/assets/images/post/test.jpeg")),
    filename: "test.jpeg"
  )
  post.save!
end

Post.create!ではバリデーションエラーに引っかかってしまいました。
Post.newからのpost.save!とすることで成功しました!!

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