我正在尝试创建一个 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 参数的原因。有没有办法防止这种情况发生,或者我对整个问题的看法完全错误?