Rails 5.1 API - 嵌套资源的不正确url_for



给定此路由结构:

路线:

  namespace :api do
    resources :templates do
      resources :template_items    
    end
  end

我搭建了template_items控制器的脚手架(但无法准确回忆起我指定的内容),但它给了我这个创建操作:

  # 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

该位置引发错误:

NoMethodError (undefined method `template_item_url' 
for #<Api::TemplateItemsController:0x007fe84774fba8>

所以我把它改成:

url_for([:api, @template_item])

这也失败了:

NoMethodError (undefined method `api_template_item_url'

所以我尝试了:

url_for([:api, :template, @template_item])

失败了:

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]):

我已经阅读了文档,但它似乎没有解释如何对嵌套资源执行此操作。

为嵌套资源生成位置 URL 的正确方法是什么?

从文档中一点也不明显,但我想通了:

location: url_for([:api, @template_item.template, @template_item])

是如何做到的。

最新更新