Render a view in Rails 5 API
You don't need to uncomment config.api_only = true
for this purpose, just inherit your controller from ActionController::Base
, or do it in your ApplicationController
(default for common rails generation).
Code:
- For this controller only
YourController < ActionController::Base
- For all apllication
ApplicationController < ActionController::Base
How to render file in Rails 5 API?
If I change the parent class to ActionController::Base everything works as expected. But I don't want to inherit the bloat of full class, I need slim API version.
Yes, if you serve index from ApplicationController, changing its base class would affect all other controllers. This is not good. But what if you had a specialized controller to serve this page?
class StaticPagesController < ActionController::Base
def index
render file: 'public/index.html'
end
end
This way, you have only one "bloated" controller and the others remain slim and fast.
Rails 5 API - How to respond with HTML on a specific controllers as an exception?
According to the Layouts and Rendering Guide:
When using html: option, HTML entities will be escaped if the string is not marked as HTML safe by using html_safe method.
So you just need to tell it the string is safe to render as html:
# modified this line, though could be done in the actual render call as well
html = "<html><head></head><body><h1>Holololo</h1></body></html>".html_safe
respond_to do |format|
format.html {render html: html, :content_type => 'text/html'}
end
Related Topics
How to Enable Compression in Ruby on Rails
Ruby - Create Singleton with Parameters
Active Admin: Sorting on Multiple Columns
Bundle Command Not Found Windows X64
Accessing Nested Model Attributes Inside a Fields_For Without Using Formbuilder
How to Get Generators Call Other Generators in Rails 3
Mail Gem - How to Clean Up the Body String
Ruby Operator Overloading Question
Reinstall Every Gem for Each Ruby Version
Split Array Up into N-Groups of M Size
Does Concurrency Happen Even When Only One Thread Is in a Thread Pool
Require Lib in Rspec with Ruby 1.9.2 Brings "No Such File to Load"
How to Run and Debug Ruby on Rails from Visual Studio Code
Referencing Model with String Input