作为一名RubyonRails开发人员,我的职业生涯才刚刚开始我正在网上读一本名为"RubyonRails教程(Rails5)"的书使用Rails学习Web开发"我按照书中的说明制作了一个"你好世界"应用程序。
app/controller/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
现在我收到错误
缺少模板application/hello with{:locale=>[:en],:formats=>[:html],:variations=>[],:handlers=>[:raw,:erb,:html,
:builder、:ruby、:coffee、:jbuilder]}。搜索位置:app_path/app/views
我有
/app/view/layouts/application.html.erb
在我的项目中,所以理论上应该是这样的视图,不是吗?
那么我是不是错过了什么?我该怎么修?
缺少模板应用程序/hello with{:locale=>[:en],:formats=>[:html],:variations=>[],:handlers=>[:raw,:erb,:html、:builder、:ruby、:coffee、:jbuilder]}。搜索位置:app_path/app/views
除了@Sujan Adiga的回答之外,render :text
还误导人们认为它会用text/plain
MIME类型来呈现内容。然而,render :text
实际上直接设置了响应主体,并继承了默认的响应MIME类型,即text/html
。因此Rails试图找到HTML模板,如果找不到,就会抛出错误。
为了避免这种情况,您可以使用content_type
选项将MIME类型设置为text/plain
,也可以仅使用render :plain
render text: "hello world!", content_type: 'text/plain'
或
render plain: "hello world!"
尝试
render plain: "hello world!"
执行render text: ...
时,它会尝试渲染名为hello.erb|haml|jbuilder|...
的模板,并将text= "hello world!"
作为数据传递。
参考
render html: "hello, world!"
将完成的工作