在Rails 4中使用show action设置非冲突的顶层路径

时间:2013-11-10 13:44:54

标签: ruby-on-rails ruby routes

我有一个用户控制器应用程序,我希望将它作为路径中的顶级路径,例如:

get ':id' => 'users#show', as: :user_profile

to_param中的User方法是:

def to_param
  self.username
end

因此,当您点击“/ rodrigo”时,它将使用username =“rodrigo”查找User对象。到目前为止,非常好。

但是我也有一些静态页面,我也希望有更多路径,例如about,terms,

controller :home do
  get 'about',       to: :about,    as: 'about'
  get 'help',       to: :help,     as: 'help'
  get 'terms',      to: :terms,    as: 'terms'
  get 'privacy', to: :privacy,  as: 'privacy'
end

当我尝试访问任何这些静态页面时,我会得到:

NoMethodError in Users#show
Showing /Users/rodrigovieira/Code/golaco/app/views/users/show.html.erb where line #1 raised:

 undefined method `name' for nil:NilClass

此外,我的users#show路由是在routes.rb中静态页面路由之前定义的。

也就是说,Rails认为我在谈论用户对象。我该如何规避这个问题?

我很确定这是可能的。我感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

Rails路由按照指定的顺序进行匹配,因此如果您有资源:获取'photos / poll'之上的照片,资源行的show action路线将在获取行之前匹配。要解决此问题,请将获取行移到资源行上方,以便首先匹配。

Golaco::Application.routes.draw do
  # Institutional/Static pages 
  controller :home do
    get 'about', to: :about, as: 'about'
    get 'help', to: :help, as: 'help'
    get 'terms', to: :terms, as: 'terms'
    get 'privacy', to: :privacy, as: 'privacy'
  end
  get ':id' => 'users#show', as: :user_profile 
  resources :users, path: "/", only: [:edit, :update] 
  devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' } 
  root 'home#index' 
end