gpt4 book ai didi

ruby-on-rails - 有条件地包含带有 RABL 的子节点

转载 作者:行者123 更新时间:2023-12-03 17:34:30 27 4
gpt4 key购买 nike

当我使用 rabl 为标准 RESTful Controller 方法返回 JSON 时,我想我有一个非常基本的情况......

首先,假设我与 parent 和 child 之间存在典型的一对多关系(假设客户和帐户):

class Customer < ActiveRecord::Base
has_many :accounts
end

在我的客户 Controller 中,我有索引和编辑 - 索引我只想返回所有客户(没有帐户)并编辑我想返回具有所有帐户的特定客户的位置。对于索引,我不想因为明显的性能 (N+1) 原因而返回帐户。

在我的 rabl 中,我有以下内容:
#index.rabl (for listing all customers)
collection :@customers
extends "customers/_customer"


#edit.rabl (for editing a single customer)
object :@customer
extends "customer/_customer"

我将 _customer.rabl 重用于索引和编辑。
#_customer.rabl
object :@customer
attributes :name, ......

if @include_accounts
child :accounts do
extends "accounts/_account"
end
end

我在我的编辑( Controller )中设置了 @include_accounts 而不是索引 - 但这不起作用 - 基本上这里的实例变量(@include_accounts)永远不会被传递下去。实现这一点的正确模式是什么?

最佳答案

尽管 rails-rabl gem 声称它更快,但我发现模板对于条件表达式并不灵活 - 请参阅 rabl-rails 自述文件:实例变量。

关于ruby-on-rails - 有条件地包含带有 RABL 的子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15651121/

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