Rails Routing (root :to => ...)

80,296

Solution 1

Had this same problem and this worked for me:

root :to => "pages#show", :id => '1'

Solution 2

As of Rails 4.0, you can declare the root route like this:

root 'controller#action'

Solution 3

I'm using Rails 5.1 to point the home page to a specific blog. In config/routes.rb I have ...

root 'blogs#show', {id: 1}

This will point the root route to /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

Solution 4

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#show action for the page with the name "landing". This is a bit more readable:

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.

Solution 5

Try:

 match 'pages/show/:id' => 'pages#show', :as => :root

In Rails console. rake routes | grep root, should show something like:

root     /pages/show/:id(.:format)      {:controller=>"pages", :action=>"show"}

Hope that helps.

Share:
80,296
Joern Akkermann
Author by

Joern Akkermann

I'm a freelancing web-developer with the will to learn more and more and more and more :)

Updated on July 09, 2022

Comments

  • Joern Akkermann
    Joern Akkermann almost 2 years

    I know how to set the routes root of my rails app to a controller and an action.

    But how to add an id?

    /pages/show/1 should be the root.

    How do I set this?

  • msanteler
    msanteler almost 10 years
    This is good except that root_path() is now adding ?id=1 to the url when linked from elsewhere in the app...
  • dlu
    dlu about 8 years
    But how do you incorporate the :id into the route?
  • BenKoshy
    BenKoshy about 8 years
    @MatthewD - curious why would you want the root route to point to an id of one?
  • NBSamar
    NBSamar over 4 years
    @dlu We can pass extra parameters. root 'controller#action', {your_params}