Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing form submission to a different controller

How do I specify the Controller and Action in a form submission? I am trying to use a 'Clients' Controller to create an Account and an associated Person ('Client').

Here are the pertinent models. A Person belongs either to an Account directly (which I am calling a 'Client') or to a Location and Organization within an Account.

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

And here is the form to create a 'Client' I am trying to make along with the rest of the code:

<%= 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

And here are my routes:

ShopManager::Application.routes.draw do

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

get 'clients/new'
post 'clients'

end

When trying to render the form, I get the following error:

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 />
like image 330
Corey Quillen Avatar asked Aug 21 '11 03:08

Corey Quillen


1 Answers

You have to say this in routes.rb

resources :clients

In the form, specify the url as clients_path with method as post:

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

For more information how rails handles REST urls: http://microformats.org/wiki/rest/urls

like image 72
Arun Kumar Arjunan Avatar answered Nov 10 '22 15:11

Arun Kumar Arjunan