How to render and return html using render_to_string in rails?

In our case, we had an item object that had different parts of an article body. We had to render that article’s body and join each part to make the article’s body.

We were struggling to get the rendered HTML in rails. But rails had render_to_string method that does exactly what we were looking for. It does the rendering and returns the HTML. Following is the code:

@article_rows.each_with_index do |item, index|
   article_parts += render_to_string item
end

Inside the view, we could easily use the render method to properly display it on the client end. But we needed this on the controller end. Actually, we were writing an API and the API needed the article’s body as HTML. Finally, we were able to assign the accumulated HTML inside the body property of the article object. See the code below:

@article.body = article_parts;
render json: JSON.pretty_generate(@article.as_json)

Source