2011-08-21 35 views
5

如何在表單提交中指定Controller和Action?我正在嘗試使用「客戶」控制器創建帳戶和關聯人員(「客戶」)。將表單提交到不同的控制器

下面是相關的模型。一個人直接屬於一個賬戶(我稱之爲「客戶」),或屬於一個賬戶內的地點和組織。

class Account < ActiveRecord::Base 
    has_many :organizations 
    has_many :persons, :as => :linkable 

    accepts_nested_attributes_for :organizations 
end 

class Person < ActiveRecord::Base 
    belongs_to :linkable, :polymorphic => true 
end 

這裏是創建一個「客戶」我試圖讓隨着其餘代碼形式:

<%= form_for @account, :url => { :controller => "clients_controller", 
           :action => "create" } do |f| %> 

<%= f.fields_for :persons do |builder| %> 
    <%= builder.label :first_name %><br /> 
    <%= builder.text_field :first_name %><br /> 
    <%= builder.label :last_name %><br /> 
    <%= builder.text_field :last_name %><br /> 
    <%= builder.label :email1 %><br /> 
    <%= builder.text_field :email1 %><br /> 
    <%= builder.label :home_phone %><br /> 
    <%= builder.text_field :home_phone %><br />   
    <% end %> 

    <%= f.submit "Add client" %> 
<% end %> 


class ClientsController < ApplicationController 

    def new 
     @account = Account.new 
     @person = @account.persons.build 
    end 

    def create 
     @account = Account.new(params[:account]) 
     if @account.save 
      flash[:success] = "Client added successfully" 
      render 'new' 
     else 
      render 'new' 
     end 
    end 

end 

這裏是我的路線:

ShopManager::Application.routes.draw do 

resources :accounts 
resources :organizations 
resources :locations 
resources :people 
resources :addresses 

get 'clients/new' 
post 'clients' 

end 

嘗試渲染表單時,出現以下錯誤:

ActionController::RoutingError in Clients#new 

Showing C:/Documents and Settings/Corey Quillen/My 
Documents/rails_projects/shop_manager/app/views/clients/new.html.erb where line #1 
raised: 

No route matches {:controller=>"clients_controller", :action=>"create"} 
Extracted source (around line #1): 

1: <%= form_for @account, :url => { :controller => "clients_controller", :action =>  
    "create" } do |f| %> 
2: 
3: <%= f.fields_for :persons do |builder| %> 
4: <%= builder.label :first_name %><br /> 

回答

12

您在routes.rb中

resources :clients 

說,這在形式,方法後指定網址爲clients_path:

<%= form_for @account, :url => clients_path, :html => {:method => :post} do |f| %> 
--- 
<% end 

欲瞭解更多信息軌如何處理REST網址:http://microformats.org/wiki/rest/urls

+0

您可以請發佈行號碼9? –

+1

這完美的作品!謝謝你的幫助!當我發佈我的最新評論時,我在帳戶模型中缺少accep_nested_attributes_for:個人。對於那個很抱歉。 –

+0

不客氣:-) –

相關問題