JSON をクライアントに送り返すために RABL で使用している Rails API があります。showモデルのandindexアクションが必要Questionです。この例では、Question has_many Answers.
RABL で nil オブジェクトをどのように処理しますか? (渡され.answersたquestionオブジェクトが存在しない) オブジェクトを呼び出しているため、API はエラーをスローします。nilquestion_id
RABL の関連部分をif以下のようにラップしてquestion、存在しない a によってエラーが発生しないようにすることができます。
# 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"