我有一个rails api,正与rabl一起使用它将json发送回客户端。对于show
模型,我需要index
和Question
操作。在本例中,aQuestion has_many Answers.
你怎么处理拉布尔的零对象?api抛出一个错误,因为我正在对.answers
对象调用question
(传入的nil
不存在)。
我可以把rabl的关联部分用下面这样的question_id
来包装,这样不存在的if
不会导致错误,
# 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
但是,当我调用
question
时,我得到的结果是:/api/questions/id_that_doesn't_exist
而不仅仅是{answer_id:null}
。我试着把整个node元素包装成这样的
{}
,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
但是我的
if
操作不会返回index
,因为从集合调用时不存在node(:answer_id)
。有办法让两种行为同时发生吗?
# questions/index.rabl
collection @questions
extends "questions/show"
最佳答案
实际上,我在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
关于ruby-on-rails - Rails JSON API,如何处理RABL中的nil对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19580997/