Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4mailboxer

The method to redirect from one page to other on ruby on rails


In my code, I use something like:

<li><%= link_to "Find a meal", {:controller =>'microposts', :action => 'index'} %></li> 

to redirect to another page.

When I studied the mailbox part, I mentioned the code is:

<li><%= link_to "Inbox", mailbox_inbox_path %></li>

And this kind of notations appear in other places of this tutorial as well. I thought mailbox_inbox_path is a variable already defined somewhere. But I can't find it.

This is the tutorial of inbox messaging.


Solution

  • mailbox_inbox_path is not a variable. It's a route helper method generated by Rails based on your routes definition in your routes.rb file. Do a:

    bundle exec rake routes
    

    Then, you will be able to see all the available routes for your Rails app and in the leftmost column, you will see the Rails generated helper methods. Just add a _path or _url to them and you can use them in your views rather than manually specifying controller and action to link_to.

    In your particular example from the tutorial, you have the following in the routes.rb file:

    get "mailbox/inbox" => "mailbox#inbox", as: :mailbox_inbox
    

    Now, if you do a: bundle exec rake routes, you will see this:

           Prefix Verb URI Pattern              Controller#Action
    mailbox_inbox GET  /mailbox/inbox(.:format) mailbox#inbox
    

    So, in the leftmost column you see mailbox_inbox which is generated by Rails and you can use this mailbox_inbox_path or mailbox_inbox_url in your views as they are available as view helper methods.

    See this documentation and resources documentation for some more information on this.