【问题标题】:Rails JSON API, how to deal with nil object in RABL?Rails JSON API,如何处理 RABL 中的 nil 对象?
【发布时间】:2013-10-25 04:15:12
【问题描述】:

我有一个 Rails API,我使用它与 RABL 一起将 JSON 发送回客户端。我需要为Question 模型设置showindex 操作。在此示例中,Question has_many Answers.

如何处理 RABL 中的 nil 对象? API 引发错误,因为我在 question 对象上调用 .answers,该对象是 nil(传入的 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"

【问题讨论】:

  • 在你的控制器中有 if 语句并在那里显式渲染空对象怎么样?
  • 这似乎有点骇人听闻,但它确实使错误消失了。如果我返回{},如果对象为零,我会从调用中返回[]。这可能是比错误更好的解决方案。

标签: ruby-on-rails ruby json api rabl


【解决方案1】:

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

您可以添加一个 :unless 块,以防止它在尝试访问 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

【讨论】:

    猜你喜欢
    • 2011-10-13
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2023-03-23
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多