Ruby on rails 如何实现根路由和获取;索引“;翻到同一页
我想所有以下网址的作品Ruby on rails 如何实现根路由和获取;索引“;翻到同一页,ruby-on-rails,ruby-on-rails-4,routing,routes,Ruby On Rails,Ruby On Rails 4,Routing,Routes,我想所有以下网址的作品 localhost:3000(在现实世界中,www.example.com) localhost:3000/index(在现实世界中,www.example.com/index) localhost:3000/home(在现实世界中,www.example.com/home) 这些URL将路由到同一位置-index.html.erb。换句话说,同一控制器的相同操作(静态页面索引) 我知道这个问题可以通过以下方式解决: root "static_pages#index"
- localhost:3000(在现实世界中,www.example.com)
- localhost:3000/index(在现实世界中,www.example.com/index)
- localhost:3000/home(在现实世界中,www.example.com/home)
root "static_pages#index"
get "index" => "static_pages#index", :as => :index
get "home" => "static_pages#index", :as => :home
简短的问题是“有没有一种方法可以在一个编码语句中实现这些路由,或者以更有效的方式实现这些路由?”一种可能的解决方案意味着不止一行,即使用范围使其更干净,您将有两行额外的代码,但我发现它更可读:
scope :path => '/', :controller => :static_pages do
get 'index' => :index, :as => 'index'
get 'home' => :index, :as => 'home'
end
通过这种方式,您可以明确为所有路由和路径(第一部分)使用哪个控制器。我认为这可以很好地将情况传达给读者(将来可能是您),为什么您希望使其更高效?这样做有什么错?我认为会发生一些代码重复,而不是rails(我的意思是不太漂亮的代码)。谢谢你的回答。我接受它看起来更像rails,但根路径或根url不再工作。你可以在你的范围内或范围外添加
根:'static_pages#index'
。这是一个可能的解决方案,可能不符合你的期望,因为需要更多的代码来解决问题。