Rails 3:命名参数路由break link_to

时间:2011-08-05 18:59:32

标签: ruby-on-rails-3 routes nested-routes

我正在尝试创建一个Rails应用程序,该应用程序按组和子组划分用户,并为每个子组提供自定义站点。我认为最简单的方法是使用命名参数创建范围:

scope ":group/:subgroup/" do
devise_for :users
    resources :users
end

“rake routes”然后产生这个:

       users GET    /:group/:subgroup/users(.:format)             {:action=>"index", :controller=>"users"}
             POST   /:group/:subgroup/users(.:format)             {:action=>"create", :controller=>"users"}
    new_user GET    /:group/:subgroup/users/new(.:format)         {:action=>"new", :controller=>"users"}
   edit_user GET    /:group/:subgroup/users/:id/edit(.:format)    {:action=>"edit", :controller=>"users"}
        user GET    /:group/:subgroup/users/:id(.:format)         {:action=>"show", :controller=>"users"}
             PUT    /:group/:subgroup/users/:id(.:format)         {:action=>"update", :controller=>"users"}
             DELETE /:group/:subgroup/users/:id(.:format)         {:action=>"destroy", :controller=>"users"}

它完美无缺 - 除非我使用link_to:

link_to current_user.name, current_user

然后它会抛出此错误

ActionController::RoutingError in Users#index 
Showing C:/Rails/MyApp/app/views/users/_my_list.html.haml where line #8 raised: 
No route matches {:action=>"show", :controller=>"users", :group=>#<User id: 7, email: "username@domain.com", encrypted_password: "$2a$10$GdZeC0b4VaNxdsDXP...", password_salt: "$2a$sj$88gm0nttYE.7a4IHi.BNO", reset_password_token: nil, remember_token: nil, remember_created_at: nil, sign_in_count: 86, current_sign_in_at: "2011-08-05 17:18:19", last_sign_in_at: "2011-08-05 00:14:26", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", confirmation_token: nil, confirmed_at: "2010-12-09 23:08:54", confirmation_sent_at: "2010-12-09 23:08:36", failed_attempts: 0, unlock_token: nil, locked_at: nil, created_at: "2010-12-09 23:08:36", updated_at: "2011-08-05 17:18:19", name: "UserOne">}

第8行当然是我尝试使用link_to的地方。我的猜测是link_to忽略了范围,它将current_user填入了:group参数。有没有办法防止这种情况发生,或者我是否完全错误地解决了整个问题?

2 个答案:

答案 0 :(得分:0)

您的resource :users在范围内,因此您没有/users/:id路线。

你可以试试这个:

scope ":group/:subgroup/" do
  devise_for :users
end
resources :users

我不确定scope是否有shallow => true选项(我认为它确实存在,您应该使用它)。

希望有所帮助

答案 1 :(得分:0)

问题是如果没有传入组和子组,就无法访​​问用户。阅读您的错误,可以理解rails正在尝试将您的current_user转换为该组。