Alex Alex - 3 months ago 28
Ruby Question

Rails - images with Redcarpet

I'm writing a Rails application and have articles in Markdown rendered using the Redcarpet gem. I would like to include images in my articles, how would I go about doing this? Where is the correct place for the images in my application, and how would I display them from that location using markdown?

Also, if I wanted the user to be able to attach/embed an image in their article, how would I do this?

By the way, I'm using Rails 5.

Answer

It's basically the same as regular markdown. You use the following syntax:

![alt text](image_path_or_url)

This will compile to:

<img src='<path_or_url'> alt="alt text">

If the image src is a url, nothing else is necessary.

If it's a local image, you need to ensure it's accessible at the path you provided.

In Rails, the public/ directory is available as static assets in development. In production, you'd need to set config.serve_static_assets = true in app/config/environments/production.rb

So for example if you had an image at public/test.jpg then you could use this markdown:

![test image](./test.jpg)