I have a Rails API that I'm using with RABL to send JSON back to the client. I need to have a show
and index
action for a Question
model. In this example, a Question has_many Answers.
How do you deal with a nil object in RABL? The API throws an error because I'm calling .answers
on a question
object that is nil
(the question_id
passed in doesn't exist).
I could wrap the association part of the RABL with an if
like below so a question
that doesn't exist won't cause an error,
# 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
But, then when I call /api/questions/id_that_doesn't_exist
I get this returned: {answer_id:null}
instead of just {}
.
I tried wrapping the entire node element in an if
like this,
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
But then my index
action won't return the node(:answer_id)
because @question
doesn't exist when calling from a collection.
Is there a way to get both behaviors?
# questions/index.rabl
collection @questions
extends "questions/show"