I want to seed my db with some instances containing active storage attachments, but i don't how i can do it. I tried some methods but not a success.
There is my Seed.
User.create(email: "[email protected]", password: "okokok") if User.count.zero?
50.times do |i|
temp = Template.create(
title: Faker::Name.name,
description: Faker::Lorem.paragraph(2),
user: User.first,
github_link: Faker::SiliconValley.url,
category: rand(0...4)
)
puts Template.first.photo
temp.photo.attach(Template.first.photo)
end
Thx for your help
It's also in the documentation guide since a couple of days:
http://edgeguides.rubyonrails.org/active_storage_overview.html#attaching-file-io-objects
Sometimes you need to attach a file that doesn’t arrive via an HTTP request. For example, you may want to attach a file you generated on disk or downloaded from a user-submitted URL. You may also want to attach a fixture file in a model test. To do that, provide a Hash containing at least an open IO object and a filename:
@message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf')
When possible, provide a content type as well. Active Storage attempts to determine a file’s content type from its data. It falls back to the content type you provide if it can’t do that.
@message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf', content_type: 'application/pdf')
If you don’t provide a content type and Active Storage can’t determine the file’s content type automatically, it defaults to application/octet-stream.
Ok i found a solution, i post it for guys in the same situation:
temp.photo.attach(
io: File.open('storage/3n/GG/3nGGV5K5ucYZDYSYojV8mDcr'),
filename: 'file.png'
)
If you have more easiest solutions share it ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With