活跃存储种子 Rails

Active storage seed Rails

我想在我的数据库中植入一些包含活动存储附件的实例,但我不知道该怎么做。我尝试了一些方法但没有成功。

有我的种子。

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

谢谢你的帮助

好的,我找到了解决方案,我 post 它适用于处于相同情况的人:

temp.photo.attach(
    io: File.open('storage/3n/GG/3nGGV5K5ucYZDYSYojV8mDcr'),
    filename: 'file.png'
  )

如果您有更简单的解决方案,请分享它;)

几天前它也在文档指南中:

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.