开发者

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

开发者 https://www.devze.com 2023-03-21 18:51 出处:网络
I have a Course model with 2 associations to another model, Tree: belongs_to:interaction_outline, :class_nam开发者_如何学Pythone => \"Tree\",

I have a Course model with 2 associations to another model, Tree:

belongs_to  :interaction_outline, :class_nam开发者_如何学Pythone => "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.

@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.

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

精彩评论

暂无评论...
验证码 换一张
取 消