Ruby-on-rails Rails 路由(root :to => ...)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6514950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Routing (root :to => ...)
提问by Joern Akkermann
I know how to set the routes root of my rails app to a controller and an action.
我知道如何将 Rails 应用程序的路由根设置为控制器和操作。
But how to add an id?
但是如何添加一个id呢?
/pages/show/1should be the root.
/pages/show/1应该是根。
How do I set this?
我该如何设置?
回答by Matthew D.
Had this same problem and this worked for me:
有同样的问题,这对我有用:
root :to => "pages#show", :id => '1'
回答by Brian Petro
As of Rails 4.0, you can declare the root route like this:
从Rails 4.0 开始,您可以像这样声明根路由:
root 'controller#action'
回答by SMHauck
I'm using Rails 5.1 to point the home page to a specific blog. In config/routes.rb I have ...
我正在使用 Rails 5.1 将主页指向特定的博客。在 config/routes.rb 我有...
root 'blogs#show', {id: 1}
This will point the root route to /blogs/1
这会将根路由指向 /blogs/1
I'm doing this on a blog site I'm building. The first blog will be the main site blog as well as the homepage.
我正在我正在建立的博客网站上这样做。第一个博客将是主站点博客和主页。
Cheers
干杯
回答by Powers
Matthew's solution works, but I think it is more readable to fetch the object. For example, let's say you want to root to the Page#showaction for the page with the name "landing". This is a bit more readable:
马修的解决方案有效,但我认为获取对象更具可读性。例如,假设您想要根到Page#show名为“landing”的页面的操作。这更具可读性:
root :to => "pages#show", :id => Page.find_by_name("landing").id
From a performance perspective, this solution is worse because it requires an additional database query, but this solution is more readable if performance is not a high priority.
从性能的角度来看,这个解决方案更糟糕,因为它需要额外的数据库查询,但如果性能不是高优先级,这个解决方案更具可读性。
回答by Christian Fazzini
Try:
尝试:
match 'pages/show/:id' => 'pages#show', :as => :root
In Rails console. rake routes | grep root, should show something like:
在 Rails 控制台中。rake routes | grep root, 应显示如下内容:
root /pages/show/:id(.:format) {:controller=>"pages", :action=>"show"}
Hope that helps.
希望有帮助。
回答by Abdalhaqq Muhammad Saih
Use Rails 5.1 Add this to the config/routes.rb
使用 Rails 5.1 将此添加到 config/routes.rb
root 'pages#show', {id: 1}

