Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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.

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

like image 228
Matt Garland Avatar asked Jul 19 '11 22:07

Matt Garland


1 Answers

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}}}} ) 
like image 107
Wizard of Ogz Avatar answered Oct 28 '22 00:10

Wizard of Ogz