使用嵌套资源调用“new”方法的路由错误

时间:2011-12-21 07:17:50

标签: ruby-on-rails-3.1 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

在routes.rb中我有

resources :customers do
  resources :locations
end    

创建新地点的代码是

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

当我尝试创建新位置时,我收到以下错误

路由错误

没有路线匹配{:action =&gt;&#34; show&#34;,:controller =&gt;&#34; locations&#34;,:customer_id =&gt;#,:id =&gt;#} < / p>

为什么:action =&gt;&#34; show&#34;被调用而不是&#34; new&#34;?

rake路由输出

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"}

locations_controller.rb中新操作的控制器代码是

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

我不明白错误,我有另外两个嵌套资源正常工作,检查了所有代码,看起来完全一样...... 是否有可能&#34; location&#34;是保留字,还是有缺失/错误的东西?

2 个答案:

答案 0 :(得分:1)

好的,发现了问题。

在app / views / locations / _form.html.erb中 由app / views / locations / new.html.erb

调用

有一个错误路径助手的链接:

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

我已将其更改为

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

现在一切正常

答案 1 :(得分:0)

尝试在image_tag上放置一个右括号。

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