主动存储种子 Rails [英] Active storage seed Rails

查看:35
本文介绍了主动存储种子 Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的种子.

User.create(email: "test@ok.com", password: "okokok") 如果 User.count.zero?50. 次做 |i|temp = Template.create(标题:Faker::Name.name,描述:Faker::Lorem.paragraph(2),用户:用户第一,github_link: Faker::SiliconValley.url,类别:兰特(0...4))把 Template.first.phototemp.photo.attach(Template.first.photo)结尾

感谢您的帮助

解决方案

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

http://edgeguides.rubyonrails.org/active_storage_overview.html#附加文件 io 对象

<块引用>

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

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

<块引用>

如果可能,还要提供内容类型.主动存储尝试从数据中确定文件的内容类型.它回落到如果它不能这样做,请提供您提供的内容类型.

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

<块引用>

如果您不提供内容类型且 Active Storage 无法确定文件的内容类型自动,默认为应用程序/八位字节流.

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

解决方案

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.

这篇关于主动存储种子 Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆