简体   繁体   English

如何在活动记录 to_json 中包含嵌套和兄弟关联?

[英]How to include nested and sibling associations in active record to_json?

I have a Course model with 2 associations to another model, Tree:我有一门课程 model 与另一个 model,树有 2 个关联:

belongs_to  :interaction_outline, :class_name => "Tree", 
                                  :foreign_key => "interaction_outline_id"
belongs_to  :token_outline, :class_name => "Tree", 
                                  :foreign_key => "token_outline_id"

I read this and was able to include sibling associations in my controller.我阅读了这篇文章,并且能够在我的 controller 中包含兄弟关联。

@course.to_json(:include=> [:interaction_outline, :token_outline]

I was also able to get multiply nested associations:我还能够获得多重嵌套关联:

@course.to_json(:include=>{:interaction_outline=> 
                              {:include=> {:tree_node=> 
                                     {:include=> :definition}}}} )  

BUT I cannot get both sibling AND multiply nested includes:但我不能同时获得兄弟和多重嵌套包括:

@course.to_json (:include=> [{:interaction_outline=> 
                               {:include=> {:tree_node=> 
                                    {:include=> :definition}}}}, 
                            {:token_outline=> 
                               {:include=> {:tree_node=> 
                                   {:include=> :definition}}}} ] ) 
#NoMethodError (undefined method `macro' for nil:NilClass)
#the error you get when the syntax or the association is wrong

I tried this, too:我也试过这个:

@course.to_json (:include=> [:interaction_outline=> 
                               {:include=> {:tree_node=> 
                                   {:include=> :definition}}}, 
                          :token_outline=> 
                             {:include=> {:tree_node=> 
                                    {:include=> :definition}}} ] ) 
#same error

What is the right syntax here?这里的正确语法是什么?

You're really close.你真的很亲近。 Just use hash notation instead of array.只需使用 hash 表示法而不是数组。

@course.to_json (:include=> {:interaction_outline=> 
                               {:include=> {:tree_node=> 
                                    {:include=> :definition}}}, 
                             :token_outline=> 
                               {:include=> {:tree_node=> 
                                   {:include=> :definition}}}} ) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM