Rails - 在嵌套资源中干燥新的/编辑页面

时间:2012-09-09 09:49:02

标签: ruby-on-rails forms routes dry nested-resources

当我有一个扁平的资源结构时,我的多个嵌套资源级别的新页面和编辑页面都运行正常。由于嵌套资源是为了使结构更具逻辑性,因此这些页面有点破碎。 我为每个模型创建了一个表单模板,其开头如下:

<%= simple_form_for @contact, html: {:class => "well form-vertical"} do |f| %>

这非常适用于非嵌套资源(如上面的Contact),允许创建和更新操作按预期工作。

但是,使用嵌套资源(例如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

2 个答案:

答案 0 :(得分:0)

<%= simple_form_for(@contact, :html => {:class => "well form-vertical"}) do |f| %>使用而不是

<%= simple_form_for @contact, html: {:class => "well form-vertical"} do |f| %>

答案 1 :(得分:0)

事实证明,这完全是采取这个问题的错误方法。我改为将我的创建路由重新编写为直接发送到/:controller,然后使用simple_form_for @contact, html: {class: "well form-vertical"} do |f|