没有路由与嵌套资源匹配

时间:2011-12-06 20:50:48

标签: ruby-on-rails database routes nested associations

我有两个关联的表。 VenuesSpecialsvenue可以包含多个specials。用户创建场地后,我希望允许他们在venues#index页面上创建特殊场景。通过使用嵌套资源,我获得了所需的URL:/venues/5/specials/new

但是,我当前的代码结果为:No route matches {:controller=>"specials", :format=>nil}

我猜这个错误与我的SpecialsController以及def newdef create函数有关。 我希望URL能够将我带到一个表单页面,在那里我可以输入特殊内容的新数据

<%= link_to 'Add Special', new_venue_special_path(venue) %>



App1::Application.routes.draw do

  resources :venues do 
    resources :specials
end


def new
    @venue = Venue.find(params[:venue_id])
      @special = @venue.specials.build
        respond_to do |format|
        format.html # new.html.erb
        format.json { render json: @special }
       end
      end


  def create
    @venue = Venue.find(params[:venue_id])
    @special = @venue.specials.build(params[:special])


    respond_to do |format|
      if @special.save
        format.html { redirect_to @special, notice: 'Special was successfully created.' }
        format.json { render json: @special, status: :created, location: @special }
      else
        format.html { render action: "new" }
        format.json { render json: @special.errors, status: :unprocessable_entity }
      end
    end
  end

回溯

Started GET "/venues/4/specials/new" for 127.0.0.1 at 2011-12-06 23:36:01 +0200
  Processing by SpecialsController#new as HTML
  Parameters: {"venue_id"=>"4"}
  [1m[36mVenue Load (0.2ms)[0m  [1mSELECT "venues".* FROM "venues" WHERE "venues"."id" = $1 LIMIT 1[0m  [["id", "4"]]
Rendered specials/_form.html.erb (1.9ms)
Rendered specials/new.html.erb within layouts/application (2.6ms)
Completed 500 Internal Server Error in 97ms

ActionView::Template::Error (No route matches {:controller=>"specials", :format=>nil}):
    1: <%= form_for(@special) do |f| %>
    2:   <% if @special.errors.any? %>
    3:     <div id="error_explanation">
    4:       <h2><%= pluralize(@special.errors.count, "error") %> prohibited this special from being saved:</h2>
  app/views/specials/_form.html.erb:1:in `_app_views_specials__form_html_erb__2784079234875518470_70162904892440'
  app/views/specials/new.html.erb:7:in `_app_views_specials_new_html_erb__115378566176177893_70162906293160'
  app/controllers/specials_controller.rb:30:in `new'

Rendered /Users/andrewlynch/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.3/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (0.7ms)

1 个答案:

答案 0 :(得分:2)

redirect_to @special

这将默认为“specials_path”,但您使用的是venue_special_path

你可能想要:

redirect_to [@venue, @special]

并且在表格中您将需要相同的内容:

<%= form_for([@venue, @special]) do |f| %>

基本上 - 问题是你有一个嵌套资源...这意味着你要声明一个url路径的每个地方(包括像form_for这样的隐式地方)都必须用@venue和@special替换,而不只是@special。

你可能会在你生成的脚手架代码中的其他地方遇到同样的“错误”...只是做同样的事情,你应该做得很好。

相关问题