31

In rails, there are a lot of helpers to direct our actions, like collections_path new_member_path edit_member_path and so on.

But where is the root? Is there a helper always points to my homepage?

Lai Yu-Hsuan
  • 27,509
  • 28
  • 97
  • 164

1 Answers1

52

These helpers exist, but you have to set your root url before, in config/routes.rb:

root :to => "controller#action"

You can use root_url and root_path afterwards.

Be warned that there's a catch when doing redirections with the _path helpers, you should use the _url ones when redirecting (see @LanguagesNamedAfterCoffee's comment for the details).

Benoit Garret
  • 14,027
  • 4
  • 59
  • 64
  • 10
    Just remember that whenever you are using `redirect_to` you will have to use `root_url`. – LanguagesNamedAfterCofee Sep 21 '11 at 19:25
  • 1
    Thanks for the clarification, I didn't know that. Out of curiosity: what does this breaks? It simply doesn't work or breaks something else (back button, etc)? – Benoit Garret Sep 21 '11 at 19:43
  • 10
    The HTTP spec requires a fully qualified URL when doing 302 Redirect and friends, and it will work in some lenient browsers, but _path should not be used. (from Agile Web Development with Rails) – LanguagesNamedAfterCofee Sep 22 '11 at 14:37
  • 1
    Thanks for the precision, I posted an addendum in the answer. – Benoit Garret Sep 22 '11 at 14:43
  • Thanks for the answer! It helped me since I used redirect_to root_path and it didn't work. In config\routes.rb, I changed root: 'home#index' to root :to => 'home#index' – Alon Samuel Jan 24 '19 at 02:52