8

I'm in the very beginning of my career as a Ruby on Rails developer I'm reading online a book named "Ruby on Rails Tutorial (Rails 5) Learn Web Development with Rails" I've made an 'hello world' app following the book instructions.

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  def hello
    render text: "hello world!"
  end

end

config/routes.rb

Rails.application.routes.draw do

  root 'application#hello'

end

Now I receive that error

Missing template application/hello with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html,

:builder, :ruby, :coffee, :jbuilder]}. Searched in: app_path/app/views

I have

/app/view/layouts/application.html.erb

in my project so that should theoretically be the view, shouldn't it?

So am I missing something? How could I fix it?

  • i'm no expert but it seems it might be deprecated, this says it's deprecated https://stackoverflow.com/questions/43428991/what-to-use-instead-of-render-text-and-render-nothing-true-in-rails-5-1 and to use render plain – barlop Jan 08 '18 at 00:10

3 Answers3

7

Missing template application/hello with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html,:builder, :ruby, :coffee, :jbuilder]}. Searched in: app_path/app/views

In addition to @Sujan Adiga's answer, render :text misdirect people to think that it would render content with text/plain MIME type. However, render :text actually sets the response body directly, and inherits the default response MIME type, which is text/html. So Rails tries to find the HTML template and spits out with that error if unable to find.

To avoid this, you can either use content_type option to set the MIME type to text/plain or just use render :plain

render text: "hello world!", content_type: 'text/plain'

or

render plain: "hello world!"
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • 1
    I can't get `render text: "hello world!", content_type: 'text/plain'` to work, I get the same error as without the `content_type: "text/plain"` argument, but i've heard render text is deprecated anyway. as is mentioned here https://stackoverflow.com/questions/43428991/what-to-use-instead-of-render-text-and-render-nothing-true-in-rails-5-1 I find `render plain` works for me. – barlop Jan 08 '18 at 00:11
5

Try

render plain: "hello world!"

when you do render text: ..., it tries to render template with name hello.erb|haml|jbuilder|... and passes text= "hello world!" as data.

Ref

Sujan Adiga
  • 1,331
  • 1
  • 11
  • 20
1
render html: "hello, world!"

will do the job

mrateb
  • 2,317
  • 5
  • 27
  • 56