3

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"
jmosesman
  • 716
  • 1
  • 11
  • 24
  • how about have if statement in your controller and explicitly render empty object there? – j03w Oct 25 '13 at 04:49
  • That seems a little hacky but it does make the error go away. If I return `{}` if the object is nil I get `[]` back from the call. That might be a better solution than an error. – jmosesman Oct 27 '13 at 17:53

1 Answers1

3

I actually found the answer in the RABL documentation trying to solve another issue.

You can add an :unless block to keep it from blowing up trying to access properties on a nil object:

# 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

Section in documentation: https://github.com/nesquena/rabl#attributes

jmosesman
  • 716
  • 1
  • 11
  • 24