当我有一个扁平的资源结构时,我的多层嵌套资源的新页面和编辑页面都可以正常工作。由于嵌套资源是为了使结构更具逻辑性,因此这些页面已经有点破损。对于每个模型,我都有一个表单模板,其开头如下:
<%= simple_form_for @contact, html: {:class => "well form-vertical"} do |f| %>
这对于非嵌套资源(如上面的联系人)非常有效,允许创建和更新操作按预期工作。
但是,对于嵌套资源(例如 Service,如下所示),新操作将停止工作。当我浏览到“新”页面时,出现错误:
Error 500: undefined method `services_path' for #<#<Class:0x0b3512b4>:0xb42b2c58>
我的相关部分的 routes.rb 如下:
resources :contacts, shallow: true, :except => [ :destroy ] do
resources :accounts, shallow: true, :except => [ :destroy ] do
resources :services, :except => [ :destroy ]
end
end
联系人和服务的新建和编辑控制器操作是:
接触:
def new
@contact = Contact.new
...
def edit
@contact = Contact.find(params[:id])
服务:
def new
@service = Service.new(account_id: params[:account_id])
...
def edit
@service = Service.find(params[:id])
相关输出rake routes
是:
account_services GET /accounts/:account_id/services(.:format) services#index
POST /accounts/:account_id/services(.:format) services#create
new_account_service GET /accounts/:account_id/services/new(.:format) services#new
edit_service GET /services/:id/edit(.:format) services#edit
service GET /services/:id(.:format) services#show
PUT /services/:id(.:format) services#update
contacts GET /contacts(.:format) contacts#index
POST /contacts(.:format) contacts#create
new_contact GET /contacts/new(.:format) contacts#new
edit_contact GET /contacts/:id/edit(.:format) contacts#edit
contact GET /contacts/:id(.:format) contacts#show
PUT /contacts/:id(.:format) contacts#update