json.name = @my_object.name
if @my_object.child
json.child do
json.partial! 'children/show', :child => @my_object.child
end
else
json.child = nil
end
This is how we might nest or include parent/child relationships in jbuilder, by utilizing a jbuilder partial for the child.
It is clear here that if @my_object.child is falsey, we don't want the partial to be parsed. Normal jbuilder template parsing would not attempt to parse the 'children/show' partial.
However, the gon jbuilder module does a simple text scan of each line of the the jbuilder template looking for lines that contain the word =~ 'partial', and then it actually attempts to create output from that partial, regardless of where that partial may sit in a conditional. In cases where the partial should not be parsed, there are probably good reasons for this, and attempting to parse it might cause errors (especially "xyz" for nil:NilClass errors), since the partial is trying to access methods on the @my_object.child variable, which is nil, or at least not an object or hash.
When we have a jbuilder template like this:
This is how we might nest or include parent/child relationships in jbuilder, by utilizing a jbuilder partial for the child.
It is clear here that if
@my_object.child
is falsey, we don't want the partial to be parsed. Normal jbuilder template parsing would not attempt to parse the 'children/show' partial.However, the gon jbuilder module does a simple text scan of each line of the the jbuilder template looking for lines that contain the word =~ 'partial', and then it actually attempts to create output from that partial, regardless of where that partial may sit in a conditional. In cases where the partial should not be parsed, there are probably good reasons for this, and attempting to parse it might cause errors (especially "xyz" for nil:NilClass errors), since the partial is trying to access methods on the
@my_object.child
variable, which is nil, or at least not an object or hash.