1

我想我正在考虑路由都错了。我有一个非常简单的两个模型设置:产品和照片。产品 has_many :photos 和 Photo belongs_to :product。

Product 有一个完整的脚手架,而 Photo 有一个我正在处理的 photos_controller。

在 routes.rb 我们有:( resources :products由脚手架生成)

由于照片是产品的嵌套资源,因此我将其更改为:

resources :products do
    resources :photos
  end

最后:

root :to => "products#index"

愉快地 rake 路线吐出:

  products GET             {:controller=>"products", :action=>"index"}
  products POST            {:controller=>"products", :action=>"create"}
  new_product GET          {:controller=>"products", :action=>"new"}
  edit_product GET         {:controller=>"products", :action=>"edit"}
  product GET              {:controller=>"products", :action=>"show"}
  product PUT              {:controller=>"products", :action=>"update"}
  product DELETE           {:controller=>"products", :action=>"destroy"}
  product_photos GET       {:controller=>"photos", :action=>"index"}
  product_photos POST      {:controller=>"photos", :action=>"create"}
  new_product_photo GET    {:controller=>"photos", :action=>"new"}
  edit_product_photo GET   {:controller=>"photos", :action=>"edit"}
  product_photo GET        {:controller=>"photos", :action=>"show"}
  product_photo PUT        {:controller=>"photos", :action=>"update"}
  product_photo DELETE     {:controller=>"photos", :action=>"destroy"}
  products GET             {:controller=>"products", :action=>"index"}
  products POST            {:controller=>"products", :action=>"create"}
  new_product GET          {:controller=>"products", :action=>"new"}
  edit_product GET         {:controller=>"products", :action=>"edit"}
  product GET              {:controller=>"products", :action=>"show"}
  product PUT              {:controller=>"products", :action=>"update"}
  product DELETE           {:controller=>"products", :action=>"destroy"}
  root                     {:controller=>"products", :action=>"index"}

这意味着 products/new 中的表单将 POST 到 products#create ,然后我想重定向到 photos#new 并有一个表单用于上传由相应的 photos/new.html.erb 生成的 product_photos 将 POST 到照片#创造,对吧?

在 product_controller.rb 中:

def create
    @product = Product.new(params[:product])

    respond_to do |format|
      if @product.save
        redirect_to new_product_photo_path, :notice => 'Product was successfully created.'
      else
        render :action => "new"
      end
    end
  end

在 photos_controller.rb 中(现在):

def new
    @photo = Photo.new
  end

那么为什么哦为什么哦为什么我会得到:

Routing Error

No route matches {:controller=>"photos", :action=>"new"}

当 rake routes 明确表示我这样做时,我有一个 photos_controller,photos_controller 中有一个新动作,而 new_product_photo_path 显然要求走正确的路?(我还有一个 photos/new.html.erb 有一个简单<h1>Photos</h1>的渲染)。

我只能得出结论,我在考虑这一切都是错误的,或者我在约定优于配置中犯了一个我看不到的错误。

有人吗?

谢谢和亲切的问候,亚当

4

1 回答 1

0

更新的答案:

使用嵌套资源意味着(在这种情况下)您只能在产品的上下文中创建新照片。这意味着应用程序必须知道要创建的照片属于哪个产品。

在重定向的情况下,这意味着您必须将产品对象作为参数添加到new_product_photo_path

redirect_to new_product_photo_path(@product)

原答案:

这是因为您将其设为嵌套资源。/products/1/photos/new可能确实有效。如果您也希望能够通过它创建新照片/photos/new,则还必须添加“未嵌套”资源。

于 2010-10-23T15:03:26.963 回答