2012-02-24 72 views
5

我正在使用RABL gem来为评论的用户呈现JSON用户数据,这些用户是作为图像的子代的注释的子代。我想要做类似的东西:Rails 3.1与RABL深嵌套

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 

我知道这是不是有效的Rabl的,我也尝试过使用儿童,而不是节点,但无法访问用户数据的方式。我应该如何去做这件事,以及什么是适当的语法来做到这一点?

回答

8

我从@calvin-l得到了这个答案。诀窍是仅仅映射a.comments,然后从每条评论中以这种方式获取数据:

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 
+0

+1。这种在块中创建散列的方式可以节省几条线,但它有点令人困惑(和单一性)。我正要更新它,但是,我想这毕竟不是很糟糕。 – tokland 2012-12-13 10:13:44