在我的应用程序中,:foos
有许多 :bars
,我将每个 foo 序列化为 JSON,如下所示:
@foo.as_json(
except: [:created_at, :updated_at],
include: {
bars: { only: [:ip_addr, :active] }
}
)
这给了我以下信息:
{
"id" => 2,
"name" => "Hello World",
"bars" => [
{ "ip_addr" => "192.123.12.32", "active" => 0 },
{ "ip_addr" => "192.123.12.33", "active" => 1 }
]
}
如您所见,我的序列化哈希包含一个非事件栏。如何从我的哈希中排除不活跃的条形图?
如果我能做到这一点就好了:
include: { bars: { only: { :active => true }}}
我是否已将 as_json
发挥到极致?我现在需要切换到事件模型序列化程序吗?
最佳答案
我认为您可以尝试添加一些方法,例如 active_bars
,它将准确返回您需要的内容,例如:
def active_bars
bars.where active: true
end
或者您甚至可以添加新关系:
has_many :active_bars, -> { where active: true }, class_name: '..', foreign_id: '..'
然后你就可以写:
@foo.as_json(
except: [:created_at, :updated_at],
include: {
active_bars: { only: [:ip_addr, :active] }
}
)
关于ruby-on-rails - 带条件的 Rails as_json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25623971/