Rails as_json不包括所有关联

时间:2013-05-09 13:53:14

标签: ruby-on-rails ruby

为了论证,我们可以说我有腿作为我的对象。我正在尝试在其上调用as_json并包含所有关联 - 这些关联设置正确,因为它在控制台中完美运行。

这就是我所拥有的:

@legs.as_json(
  :include => {
    :shoes => {
      :include => {
        :left_shoe => {
          :include => {
            :shoe_lace => {:include => :sock}
          }
        }
      },
      :right_shoe => {
        :include => {
          :shoe_lace => {:include => :sock}
        }
      }
    }
  }
)

由于某种原因,它不包括right_shoe。它只是停在left_shoe。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我认为根据评论你的右鞋处于错误的水平。试试这个:

@legs.as_json(
  :include => {
    :shoes => {
      :include => {
        :left_shoe => {
          :include => {
            :shoe_lace => {:include => :sock}
          }
        },
        :right_shoe => {
          :include => {
            :shoe_lace => {:include => :sock}
          }
        }
      }
    }
  }
)

答案 1 :(得分:0)

你有没有尝试过这个宝石,操作JSON模型关联非常酷:

https://github.com/fabrik42/acts_as_api