【发布时间】:2013-10-25 04:15:12
【问题描述】:
我有一个 Rails API,我使用它与 RABL 一起将 JSON 发送回客户端。我需要为Question 模型设置show 和index 操作。在此示例中,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