我有两张相关的桌子。VenuesSpecials。avenue可以有许多specials。一旦用户创建了一个地点,我希望允许他们在venues#index页面上创建一个特殊的地点。通过使用嵌套资源,我获得了所需的url:/venues/5/specials/new
但是,我当前的代码结果是:No route matches {:controller=>"specials", :format=>nil}
我猜错误在于我的SpecialsControllerdef newdef create函数。
我想要这个网址带我到一个表单页面,在那里我可以输入特殊的新数据

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

最佳答案

redirect_to @special

这将默认为“特殊路径”,但您使用的是场馆特殊路径
你可能想要:
redirect_to [@venue, @special]

在表格中,你需要同样的:
<%= form_for([@venue, @special]) do |f| %>

基本上-问题是你有一个嵌套的资源…这意味着,声明url路径的每个位置(包括form_for之类的隐式位置)都必须同时替换为@venue和@special,而不仅仅是@special。
在生成的scaffold代码中,您可能会在其他地方遇到同样的“bug”…只要做同样的事,你就应该做好。

关于ruby-on-rails - 嵌套资源没有路由匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8406654/

10-11 17:34