我正在按照教程(https://blog.teamtreehouse.com/static-pages-ruby-rails(使用Rails路由呈现页面。问题是我收到一个错误,而不是应该呈现的页面。我不知道我做错了什么,因为实际上只有几个步骤。
我的代码与教程的唯一区别是微不足道的。我使用的是Videos
而不是Pages.
在config/routes.rb
:
Rails.application.routes.draw do
# This means that all paths following the pattern:
# /videos/about, /videos/home, /videos/features
# will route here!
get "/videos/:video" => "videos#show"
end
在app/controllers/videos_controller.rb"
:
class VideosController < ApplicationController
def show
render template: "videos/#{params[:page]}"
end
end
最后,我有一个静态页面,里面装满了存储在app/views/videos/videos.html.erb
中的乱码。
但是,当我运行服务器并转到0.0.0.0:3000/videos/
时,出现以下错误:
No route matches [GET] "/videos"
Rails.root: /home/mightu/Desktop/portal_rails
当我尝试0.0.0.0:3000/videos/pizza
时,我得到:
Missing template /videos with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in: * "/home/mightu/Desktop/portal_rails/app/views"
它告诉我问题是这一行:
render template: "videos/#{params[:page]}"
请帮忙谢谢
定义要/videos
的路由,如果需要所有的休息路由,你可以添加一个resources :videos
或者只是 get 'videos', to: 'videos#index'
.
您只定义了show
操作的路由,但您正在尝试获取视频的index
页面,您可以在此处查看路由的详细信息
从做开始:
Rails.application.routes.draw do
resources :videos
end
这将为您提供:
videos GET /videos(.:format) videos#index
POST /videos(.:format) videos#create
new_video GET /videos/new(.:format) videos#new
edit_video GET /videos/:id/edit(.:format) videos#edit
video GET /videos/:id(.:format) videos#show
PATCH /videos/:id(.:format) videos#update
PUT /videos/:id(.:format) videos#update
DELETE /videos/:id(.:format) videos#destroy
然后,将app/views/videos/videos.html.erb
重命名为 app/views/videos/show.html.erb
。
并将VideosController
上的show
操作修改为:
class VideosController < ApplicationController
def show
end
end
现在0.0.0.0:3000/videos/pizza
将呈现show.html.erb
模板,您将拥有一个值为 pizza
的params[:id]
。