Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 deep nesting with RABL

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?

like image 466
ramz15 Avatar asked Feb 24 '12 09:02

ramz15


1 Answers

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
like image 137
ramz15 Avatar answered Oct 18 '22 19:10

ramz15