How to return HTML directly from a Rails controller?

Ruby on-Rails

Ruby on-Rails Problem Overview


One of my model objects has a 'text' column that contains the full HTML of a web page.

I'd like to write a controller action that simply returns this HTML directly from the controller rather than passing it through the .erb templates like the rest of the actions on the controller.

My first thought was to pull this action into a new controller and make a custom .erb template with an empty layout, and just <%= modelObject.htmlContent %> in the template - but I wondered if there were a better way to do this in Rails.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

In your controller respond_to block, you can use:

render :text => @model_object.html_content

or:

render :inline => "<%= @model_object.html_content %>"

So, something like:

def show
  @model_object = ModelObject.find(params[:id])
  
  respond_to do |format|
    format.html { render :text => @model_object.html_content }
  end
end

Solution 2 - Ruby on-Rails

In latest Rails (4.1.x), at least, this is much simpler than the accepted answer:

def show
  render html: '<div>html goes here</div>'.html_safe
end

Solution 3 - Ruby on-Rails

Its works for me

def show
  @model_object = ModelObject.find(params[:id])

   respond_to do |format|
    format.html { render :inline => "<%== @model_object['html'] %>" }
  end
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNateView Question on Stackoverflow
Solution 1 - Ruby on-RailsDan McNevinView Answer on Stackoverflow
Solution 2 - Ruby on-RailsVincent WooView Answer on Stackoverflow
Solution 3 - Ruby on-RailsSelvamaniView Answer on Stackoverflow