2011-08-21 30 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

不客气:-) –

相关问题