kranz
kranz

Reputation: 621

Routing error calling "new" method with nested resource

I have two nested resources:

class Customer < ActiveRecord::Base
  has_many :locations, :dependent => :destroy
  accepts_nested_attributes_for :locations
end

class Location < ActiveRecord::Base
  belongs_to :customer
end

In routes.rb I have

resources :customers do
  resources :locations
end    

The code for creating a new location is

<%= link_to image_tag("add.png"), new_customer_location_path(@customer), :class => "button" %>

When I try to create a new location I get the following error

Routing Error

No route matches {:action=>"show", :controller=>"locations", :customer_id=>#, :id=>#}

Why :action=>"show" is invoked instead of "new"?

rake routes output is

customer_locations     GET    /customers/:customer_id/locations(.:format)                  {:action=>"index", :controller=>"locations"}
                       POST   /customers/:customer_id/locations(.:format)                  {:action=>"create", :controller=>"locations"}
new_customer_location  GET    /customers/:customer_id/locations/new(.:format)              {:action=>"new", :controller=>"locations"}
edit_customer_location GET    /customers/:customer_id/locations/:id/edit(.:format)         {:action=>"edit", :controller=>"locations"}
customer_location      GET    /customers/:customer_id/locations/:id(.:format)              {:action=>"show", :controller=>"locations"}
                       PUT    /customers/:customer_id/locations/:id(.:format)              {:action=>"update", :controller=>"locations"}
                       DELETE /customers/:customer_id/locations/:id(.:format)              {:action=>"destroy", :controller=>"locations"}

The controller code for the new action in locations_controller.rb is

before_filter :find_customer

def new
  @location = @customer.locations.new

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @location }
  end
end

I do not understand the error, I have another two nested resources that work correctly, checked all the code and it seems exactly the same... Is there a possibility that "location" is a reserved word, or is there something missing/wrong?

Upvotes: 2

Views: 383

Answers (2)

kranz
kranz

Reputation: 621

Ok, found the problem.

Inside app/views/locations/_form.html.erb which is invoked by app/views/locations/new.html.erb

there was a link with a wrong path helper:

    <%= link_to "Cancel", customer_location_path(@customer,@location) %>

I have changed it to

    <%= link_to "Cancel", customer_path(@customer) %>

and now everything works

Upvotes: 1

nmott
nmott

Reputation: 9604

Try putting a closing bracket on the image_tag.

<%= link_to image_tag("add.png"), new_customer_location_path(@customer), :class => "button" %>

Upvotes: 0

Related Questions