Rails: form_for namespaced resource

北城余情 提交于 2019-12-30 04:01:10

问题


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?


回答1:


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

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



回答2:


When you use form_for, it assumes that the appropriate path is [model_name]_path. You have to explicitly tell it the url with

form_for @user, url: admin_user_path


来源:https://stackoverflow.com/questions/10953174/rails-form-for-namespaced-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!