开发者

Rails: Routing issues

I'm working on a simple Rails app, which currently has four pages - Home, About, Contact, and Search Results. My routes.rb looks like this:

IdealmSite::Application.routes.draw do

    root:to => 'main_pages#home'
    match '/about', :to => 'main_pages#about'
    match '/contact', :to => 'main_pages#contact'开发者_如何学JAVA
    match '/search_results', :to => 'main_pages#search_results'

end

Everything works fine until I try to use the named routes as an argument to the link_to function, like this:

<%= link_to "Home", home_path %>

The output for Rails Server says this:

ActionView::Template::Error (undefined local variable or method `home_path' for #<#<Class:0x00000100eb2200>:0x00000100eaef38>):
    20:             <div id="left">
    21:   <div class="verticalmenu">
    22:    <ul>
    23:      <li><%= link_to "Home", home_path %></li>
    24:      <li><%= link_to "About", '#' %></li>
    25:      <li><%= link_to "Contact", '#' %></li>
    26:    </ul>
  app/views/layouts/application.html.erb:23:in `_app_views_layouts_application_html_erb___584831540324030083_2155170260__1382439999518380141'

Rendered /Users/idealm/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Users/idealm/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (2.5ms)
Rendered /Users/idealm/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (7.1ms)

What am I doing wrong?


When you create a route it creates helpers for you.

root => 'main_pages#home'

means that you can now use "root_path" and "root_url" in your application. If you want to have home_path you would have to do:

match '/home' => 'main_pages#home', :as => :home

That :as option is what creates the helpers whatever_path and whatever_url.

Remember you can see all your routes with:

rake routes


You want root_path instead of home_path.

I suggest running rake routes via command line to see all available routes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜