Search code examples
ruby-on-railsrubyrails-activestorage

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: "test@ok.com", 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


Solution

  • 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.