Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active storage seed Rails

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

like image 794
Ronan Louarn Avatar asked Apr 29 '18 14:04

Ronan Louarn


2 Answers

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.

like image 132
stwienert Avatar answered Oct 25 '22 14:10

stwienert


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 ;)

like image 31
Ronan Louarn Avatar answered Oct 25 '22 15:10

Ronan Louarn