且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails:form_for 命名空间资源

更新时间:2023-11-02 15:24:34

您可以添加命名空间的名称作为符号:

 

I want to set up the CRUD for users, available just for administrators of my web application. So in routes.rb:

namespace :admin do
  resources :user
end

which means this:

admin_user_index GET    /admin/user(.:format)                  admin/user#index
                 POST   /admin/user(.:format)                  admin/user#create
  new_admin_user GET    /admin/user/new(.:format)              admin/user#new
 edit_admin_user GET    /admin/user/:id/edit(.:format)         admin/user#edit
      admin_user GET    /admin/user/:id(.:format)              admin/user#show
                 PUT    /admin/user/:id(.:format)              admin/user#update
                 DELETE /admin/user/:id(.:format)              admin/user#destroy

Show, index work fine but edit and new don't. I keep getting this error in the _form first line:
undefined method `user_path' for #<#:0x007fb6645c6378>

which is this:

How can I use form_for with a namespaced resource?

You can add the namespace's name as a symbol:

 <%= form_for [:admin, @user] do |f| %>