Search code examples
ruby-on-railsrails-activestorage

Use create an record with Active Storage without ActionParameters


I try to create a record, with image, directyl with create, and in model

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'), width: 595, height: nil )

I must do at creation moment, not with .attach after, because of validation. Can we do this ?


Solution

  • You can pass a block to create. It’ll be called with the new record before it’s saved:

    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