DEV Community

Morten Trolle
Morten Trolle

Posted on

ActiveStorage: Attaching file inline in Model.create / update

In the Rails guides you learn you can attach a file to a model using the attach method on you attachment:

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

Super useful when your record is already created. But if you need to create a new record you can also attach your file directly in the create command:

Message.create(
  foo: 'baa', 
  image: {
    io: File.open(Rails.root.join('image.png')),
    filename: 'image.png'
  }
)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)