How to return HTML directly from a Rails controller?

One of my model objects has a β€œtext” column that contains the full HTML address of the web page.

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

My first thought was to bring this action to a new controller and create my own .erb template with an empty layout and just <%= modelObject.htmlContent %> in the template, but I wondered if there is a better way to do this in Rails.

+57
ruby-on-rails
Dec 24 '09 at 15:43
source share
3 answers

In the respond_to control respond_to 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 
+82
Dec 24 '09 at 15:49
source share
β€” -

In the 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 
+34
Oct. 16 '14 at 9:40
source share

His work is for me

 def show @model_object = ModelObject.find(params[:id]) respond_to do |format| format.html { render :inline => "<%== @model_object['html'] %>" } end end 
+3
Dec 27 '13 at 13:22
source share



All Articles