gpt4 book ai didi

ruby-on-rails - Rails JSON API,如何处理 RABL 中的 nil 对象?

转载 作者:数据小太阳 更新时间:2023-10-29 08:00:12 27 4
gpt4 key购买 nike

我有一个与 RABL 一起使用的 Rails API,用于将 JSON 发送回客户端。我需要为 Question 模型执行 showindex 操作。在此示例中,一个问题有_many 个答案。

你如何处理 RABL 中的 nil 对象? API 抛出错误,因为我在 nilquestion 对象上调用 .answers(question_id传入的不存在)。

我可以用 if 包裹 RABL 的关联部分,如下所示,这样一个不存在的 question 就不会导致错误,

# questions/show.rabl
object @question
attributes :id, :text

node(:answer_id) do |question|
if question != nil # <-- This if keeps the .answers from blowing up
answer = question.answers.first
answer != nil ? answer.id : nil
end
end

但是,当我调用 /api/questions/id_that_doesn't_exist 时,我得到了这个返回:{answer_id:null} 而不仅仅是 {}/.

我试过像这样将整个节点元素包装在 if 中,

if @question != nil    # <-- the index action doesn't have a @question variable
node(:answer_id) do |question|
answer = question.answers.first
answer != nil ? answer.id : nil
end
end

但是我的 index 操作将不会返回 node(:answer_id) 因为 @question 从一个调用时不存在收藏。

有没有办法同时获得这两种行为?

# questions/index.rabl
collection @questions

extends "questions/show"

最佳答案

我实际上在试图解决另一个问题的 RABL 文档中找到了答案。

您可以添加一个 :unless block 以防止它在尝试访问 nil 对象的属性时崩溃:

# questions/show.rabl
object @question
attributes :id, :text

node(:answer_id, unless: lambda { |question| question.nil? }) do |question|
answer = question.answers.first
answer != nil ? answer.id : nil
end

文档部分:https://github.com/nesquena/rabl#attributes

关于ruby-on-rails - Rails JSON API,如何处理 RABL 中的 nil 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19580997/

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