首页 文章

活动存储种子Rails

提问于
浏览
3

我想用一些包含活动存储附件的实例播种我的数据库,但我不知道我怎么做 . 我尝试了一些方法,但没有成功 .

有我的种子 .

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

谢谢你的帮助

2 回答

  • 7

    几天后它也出现在文档指南中:

    http://edgeguides.rubyonrails.org/active_storage_overview.html#attaching-file-io-objects

    有时您需要附加未通过HTTP请求到达的文件 . 例如,您可能希望附加在磁盘上生成或从用户提交的URL下载的文件 . 您可能还希望在模型测试中附加fixture文件 . 为此,提供一个至少包含一个开放IO对象和一个文件名的Hash:

    @message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf')
    

    如果可能,也提供内容类型 . Active Storage尝试从其数据中确定文件的内容类型 . 它会回退到您提供的内容类型,如果它不能这样做 .

    @message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf', content_type: 'application/pdf')
    

    如果您未提供内容类型,并且Active Storage无法自动确定文件的内容类型,则默认为application / octet-stream .

  • 1

    好的,我找到了一个解决方案,我发布给同样情况下的人:

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

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

相关问题