【发布时间】:2012-09-09 09:49:02
【问题描述】:
当我有一个扁平的资源结构时,我的多层嵌套资源的新页面和编辑页面都可以正常工作。由于嵌套资源是为了使结构更具逻辑性,因此这些页面已经有点破损。 对于每个模型,我都有一个表单模板,开头如下:
<%= 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
【问题讨论】:
-
我看到你真的没有
services_path助手。仅限account_services_path。 -
我也看到了,但是如果在我的表单中添加:
url: account_services_path(account_id: params[:account_id]),那么新操作可以正常工作,但编辑停止工作,因为编辑 url 需要:id,而不是:account_id。跨度> -
我主要关心的是保持简单,我不想仅仅因为我必须更改一行而创建一个全新的页面,而其他行都是相同的。
-
如果您使用脚手架生成器为资源创建视图,默认情况下它可能会在您的代码中插入不正确的帮助器。尝试检查您的
new页面。 -
没有脚手架,我使用 rails generate 分别创建所有模型、视图和控制器。我已经查看了正在工作的页面和不重复页面的代码,它们都没有改变,唯一的区别是我现在嵌套了一些资源,而以前它们是平面结构。
标签: ruby-on-rails forms routes dry nested-resources