How do I include nested and related associations in my to_json active record?

I have a course model with 2 associations with 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 sisters associations in my controller.

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

I also managed to get multiple nested associations:

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

BUT I can not get both brothers and repeatedly 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 correct syntax here?

+8
json ruby-on-rails activerecord
source share
1 answer

You are really there. 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}}}} ) 
+26
source share

All Articles