Railsの中でルーティングの概要3
-
25-09-2019 - |
質問
私はすべて間違っをルーティング考えていと思います。製品および写真:私は非常に単純な、2つのモデルのセットアップを持っています。製品にhas_many:belongs_toの写真や、写真:製品
写真は、私が働いているというphotos_controllerを有している製品は、完全な足場を持っています。
routes.rbを、我々は持っています:
resources :products
(足場によって生成される)
私はこれを変更します:
resources :products do
resources :photos
end
そして最後ます:
root :to => "products#index"
幸いうち、ルートの串をすくい
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"}
私は、写真の新しい#にリダイレクトすると、対応する写真/ new.html.erbによって生成されたproduct_photosをアップロードするためのフォームを持ちたい#が作成した製品への製品の形/新しい意思のPOST手段ということでしょう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"}
すくいルートが明確に私が言うとき、私はphotos_controller、photos_controllerで新しいアクションを持っている、とnew_product_photo_pathは明らかに正しい道を行くことを求めていますか? (私も何かをレンダリングするための簡単な<h1>Photos</h1>
を持っている写真/ new.html.erbを持っている)。
私は、私はこのすべての間違った方法について考え、または私は見ることができない設定より規約でエラーをしたことだということを結論付けることができます。
誰?
おかげで、種類よろしく、 アダム
解決
更新の答え:
あなたが唯一の製品のコンテキストで新しい写真を作成することができます(この場合は)ネストされたリソース手段を使用。アプリケーションが作成される写真は、に属する製品を知る必要があること。
この手段あなたのリダイレクトの場合、この手段はあなたがnew_product_photo_path
のパラメータとして、製品のオブジェクトを追加する必要があります:
redirect_to new_product_photo_path(@product)
<時間>
オリジナルの答え:
あなたはそれネストされたリソース作られているため、このです。 /products/1/photos/new
は、おそらく作業を行います。あなたも/photos/new
を経由して新しい写真を作成できるようにしたい場合は、あなたも「ネスト解除」リソースを追加する必要があります。