Rails 3.1 deep nesting with RABL
Asked Answered
U

1

5

I'm using the RABL gem to render JSON user data for users of comments which are children of annotations which are children of images. I'd like to do something similar to:

object @image

node :annotations do
  @image.annotations.map { |a| {
    :id => a.id,
    :x1 => a.x1,
    :x2 => a.x2,
    :y1 => a.y1,
    :y2 => a.y2,
    node :comments do
      @image.annotations.comments.map { |c| {
       :body => c.body, 
       :user_id => c.user_id,
       :name => User.find(c.user_id).name,
       :user_icon => user_icon(User.find(c.user_id), 'square', 30)
      }} 
    end
  }}
end

I know this isn't valid in RABL, I also tried using child instead of node, but couldn't access the user data that way. How should I go about doing this and whats the proper syntax to make this happen?

Unbuckle answered 24/2, 2012 at 9:23 Comment(0)
U
8

I got this answer from @calvin-l. The trick was to just map the a.comments then grab the data from each comment that way:

node :annotations do
  @image.annotations.map { |a| {
    :id => a.id,
    :x1 => a.x1,
    :x2 => a.x2,
    :y1 => a.y1,
    :y2 => a.y2,
    :comments => a.comments.map { |c| {
      :body => c.body,
      :created_at => c.created_at,
      :user => {
        :id => c.user.id,
        :facebook_id => c.user.facebook_id,
        :name => c.user.name,
        :username => c.user.username
      }
    }}
  }}
end
Unbuckle answered 24/2, 2012 at 18:5 Comment(1)
+1. this way of creating a hash in a block saves a couple of lines but it's somewhat confusing (and unidiomatic). I was about to update it, but well, I guess it's not so bad after all.Autotruck

© 2022 - 2024 — McMap. All rights reserved.