问题
Given this route structure:
routes:
namespace :api do
resources :templates do
resources :template_items
end
end
I scaffolded the template_items controller (but cannot recall exactly what I specified) but it gave me this create action:
# POST /template_items
def create
@template_item = TemplateItem.new(template_item_params)
if @template_item.save
render json: @template_item, status: :created, location: @template_item
else
render json: @template_item.errors, status: :unprocessable_entity
end
end
The location throws an error:
NoMethodError (undefined method `template_item_url'
for #<Api::TemplateItemsController:0x007fe84774fba8>
So I changed it to:
url_for([:api, @template_item])
which failed also:
NoMethodError (undefined method `api_template_item_url'
So then I tried:
url_for([:api, :template, @template_item])
which failed with this:
ActionController::UrlGenerationError
(No route matches
{:action=>"show",
:controller=>"api/template_items",
:template_id=>#<TemplateItemid: "b4a3921b-dcae-4902-aaf7-b2ef40e13707",
template_id: "b2f22587-a36e-469f-9485-45b7d60c0120",
content: nil,
is_completed: false,
item_type: "item",
sort: 7,
created_at: "2017-10-22 11:37:17",
updated_at: "2017-10-22 11:37:17">},
missing required keys: [:id]):
I've read the docs, but it does not appear to explain how to do this for nested resources.
What is the correct way to generate the location url for a nested resource?
回答1:
Not at all obvious from the docs, but I figured it out:
location: url_for([:api, @template_item.template, @template_item])
is how to do it.
来源:https://stackoverflow.com/questions/46873659/rails-5-1-api-incorrect-url-for-with-a-nested-resource