Render a view in Rails 5 API
Asked Answered
C

2

14

I generated an API-only rails app with Rails 5 via rails new <application-name> --api. I've decided I want to include a view for testing some things and am having issues getting a view to load.

I created a users/index.html.erb file with some text and my controller is now simply def index; end but there is nothing appearing when I hit the /users URL. I also tried commenting out the # config.api_only = true in config/application.rb but that didn't affect anything. Any suggestions on how to proceed?

Calcite answered 5/10, 2016 at 22:11 Comment(0)
G
38

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:

  1. For this controller only YourController < ActionController::Base
  2. For all apllication ApplicationController < ActionController::Base
Googolplex answered 5/10, 2016 at 22:28 Comment(3)
Thanks - the first point didn't work for me, but the 2nd point did. Thank you!Calcite
Strange, because i tested only first point, but anyway behavior is similar :)Googolplex
Expect other gotchas with rendering html views from an API app if the html endpoint ever makes use of sessions or cookies (e.g. like with devise), as these are stripped out with API only rails.Thurman
T
2

this is from the ActionController::Metal docs https://apidock.com/rails/ActionController/Metal

it says:

ActionController::Metal by default provides no utilities for rendering >views, partials, or other responses aside from explicitly calling of >response_body=, content_type=, and status=. To add the render helpers >you’re used to having in a normal controller, you can do the following:

class HelloController < ActionController::Metal
 include AbstractController::Rendering
 include ActionView::Layouts
 append_view_path "#{Rails.root}/app/views"

  def index
   render "hello/index"
  end
end

So I've tried it myself and adding just by adding the two modules actually work just fine when using it for ActionController::API

Tejeda answered 15/5, 2020 at 6:38 Comment(1)
For Rails 7, include ActionView::Layouts did the trickDeanndeanna

© 2022 - 2024 — McMap. All rights reserved.