繁体   English   中英

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

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

我有一门课程 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"

我阅读了这篇文章,并且能够在我的 controller 中包含兄弟关联。

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

我还能够获得多重嵌套关联:

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

但我不能同时获得兄弟和多重嵌套包括:

@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

我也试过这个:

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

这里的正确语法是什么?

你真的很亲近。 只需使用 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