0

我尝试使用图像创建记录,使用创建的directyl,并在模型中

Banner.create(start_at: Time.now, location: 'site', image_fr: File.new("#{Rails.root}/db/seeds/images/banners/pdfs/gift_voucher_bottom.png", 'r'), image_de: File.new("#{Rails.root}/db/seeds/images/banners/pdfs/gift_voucher_bottom.png", 'r'), 宽度: 595, 高度: nil )

由于验证,我必须在创建时执行,而不是在之后使用 .attach。我们可以这样做吗?

4

1 回答 1

1

您可以将块传递给create. 它将在保存之前使用新记录调用:

Banner.create(start_at: Time.now, location: 'site', width: 595, height: nil) do |banner|
  Rails.root.join('db/seeds/images/banners/pdfs/gift_voucher_bottom.png').open('rb') do |io|
    banner.image_fr.attach(io: io, filename: 'banner.png', content_type: 'image/png')
  end

  # ...
end
于 2018-05-03T14:48:15.520 回答