【问题标题】:Routing with rails 3.2.1使用 rails 3.2.1 路由
【发布时间】:2012-02-22 18:31:42
【问题描述】:

我刚刚通过观看 railscasts 升级到 rails 3.1.0 和 3.2.0,将一个 rails 3.0.9 应用程序升级到 rails 3.2.1。在更新之前,我(当时正在工作)的 routes.rb 文件看起来像:

match "home" => "pages#index"
match "*page" => "pages#show" 
root :to => "pages#index"

更新后我将 routes.rb 文件更改为:

match "home" => "pages#index"
match "pages/*page" => "pages#show", :format => false 
root :to => "pages#index"

我从 Rout Globbing 部分的Ruby on Rails routing 得到这个想法,以模仿 Rails 版本 3.0.x。

现在当我点击我的链接时,由:

<li><%= link_to "What We Do", "/what-we-do" %></li>

我收到此错误:

Routing Error
No route matches [GET] "/what-we-do"
Try running rake routes for more information on available routes.

rake routes produces:

    home  /home(.:format) pages#index
          /pages/*page    pages#show
    root  /               pages#index
If that is helpful.

我尝试渲染的页面名为 what-we-do.html.erb,位于 app/views/pages 中。

这是我的控制器:

class PagesController < ApplicationController

  def index
    render :home, :layout => false
  end

  def show
    render static_page 
  rescue 
    # page_not_found
  end


  private

  def static_page
    "#{RAILS_ROOT}/app/views/pages/#{params[:page]}.html.erb"
  end

  def page_not_found
    render "#{Rails.root}/public/404.html", :layout => false 
  end

end

大家有什么建议吗?

【问题讨论】:

  • 所以我想通了。我将路线切换回:match "*page" =&gt; "pages#show",但真正的问题出在我的控制器上。在 Rails 3.0.X 中,您使用 RAILS_ROOT,但在 3.1 及更高版本中,它是 Rails.root。谢谢大家

标签: ruby routing ruby-on-rails-3.2


【解决方案1】:

成员路由需要一个 ID,因为它作用于成员。集合路由不会,因为它作用于对象集合。

map.resources :users, :collection => { :customers_list=> :get }

map.resources :users, :member => { :inactive=> :post }

被视为/users/1;inactive=&gt; [:action =&gt; 'inactive', :id =&gt; 1]

【讨论】:

    【解决方案2】:

    你有一个匹配/pages/what-we-do的路由:

    /pages/*page    pages#show
    

    但是没有什么可以匹配不以/pages/ 开头的 URL(当然,/home 除外)。你仍然需要你的顶级 globbed 路由:

    match "*page" => "pages#show"
    

    如果你想匹配/what-we-do。可能你误会了this from the routing guide

    从 Rails 3.1 开始,通配符路由默认总是匹配可选的格式段。例如,如果您有这条路线:

    match '*pages' => 'pages#show'
    

    通过请求"/foo/bar.json",您的params[:pages]将等于"foo/bar",请求格式为JSON。

    变化在于您不必自己处理格式,现在它会像所有其他路由一样自动处理。

    【讨论】:

      【解决方案3】:

      路由需要是这样的 -

      match "home", :to => "pages#index"
      root :to => "pages#index"
      match ":page", :to => "pages#show" 
      

      【讨论】:

        【解决方案4】:

        您似乎没有在 routes 中提到预期的操作。如果您在任何脚手架内使用静态路由,则应在内部路由中提及该操作

        collection :controller do 
          get 'action name'
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-09
          • 1970-01-01
          相关资源
          最近更新 更多