我有一个课程模型,其中有两个与另一个模型的关联,树:
belongs_to :interaction_outline, :class_name => "Tree",
:foreign_key => "interaction_outline_id"
belongs_to :token_outline, :class_name => "Tree",
:foreign_key => "token_outline_id"
我阅读this并且能够在我的控制器中包含兄弟关联。
@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
这里的语法是什么?
答案 0 :(得分:28)
你真的很亲密。只需使用哈希表示法而不是数组。
@course.to_json (:include=> {:interaction_outline=>
{:include=> {:tree_node=>
{:include=> :definition}}},
:token_outline=>
{:include=> {:tree_node=>
{:include=> :definition}}}} )