gpt4 book ai didi

ruby-on-rails - 如何在没有 "root"节点和 rabl 的情况下使用不同的模板进行收集

转载 作者:行者123 更新时间:2023-12-04 06:17:47 25 4
gpt4 key购买 nike

我和 Rabl 一起工作了一段时间,就在今天,我遇到了一个我无法很好解决的有趣问题..

所以,我有一个从 GET ".../list/512/resources"返回的集合,这是我以前返回的示例 rabl 模板(没有 root):

collection @resources
extends "api/v1/resources/_base"

=> { [ {...}, {...}, {...} ] }

但是,现在我意识到我想根据每个资源的属性为每个资源返回不同的模板。这很容易吧?

node @resources => :resources do |resource|
if resource.type == 'Document'
partial('...', :object => resource)
elsif @resource.type == 'Folder'
partial('...', :object => resource)
end
end

=> { 资源:[ {...}, {...}, {...} ] }

但是哦!现在我不想要那里的“资源”节点..应该怎么做?我试过类似的东西:

array = []

@resources.each do |resource|
if resource.type == 'Document'
array << partial('...', :object => resource)
elsif @resource.type == 'Folder'
array << partial('...', :object => resource)
end
end

collection array

但没有成功,它返回空对象,如 => [ {}, {}, {} ]。知道我怎样才能做到这一点吗?

最佳答案

只要删除整个“@resources => :resources”就可以了(前提是这是 resources/index.json.rabl 的内容并且你的 Controller 设置了@resources)

node do |resource|
if resource.type == 'Document'
partial('...', :object => resource)
elsif @resource.type == 'Folder'
partial('...', :object => resource)
end
end

您可能想查看 https://github.com/rails-api/active_model_serializers作为 rabl 的替代品。鉴于您的用例,它可能更易于使用。

关于ruby-on-rails - 如何在没有 "root"节点和 rabl 的情况下使用不同的模板进行收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com