Rails 5.1 API-带有嵌套资源的不正确的url_for [英] Rails 5.1 API - incorrect url_for with a nested resource

查看:94
本文介绍了Rails 5.1 API-带有嵌套资源的不正确的url_for的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下路线结构:

路线:

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

我架起了template_items控制器(但无法确切地回忆起我指定的内容),但是它给了我这个创建动作:

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

该位置引发错误:

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

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

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?

推荐答案

在文档中一点都不明显,但是我发现了:

Not at all obvious from the docs, but I figured it out:

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

是怎么做的.

这篇关于Rails 5.1 API-带有嵌套资源的不正确的url_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆