DEV Community

loading...

ActiveStorage: Attaching file inline in Model.create / update

mtrolle profile image Morten Trolle ・1 min read

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

Discussion (0)

pic
Editor guide