【问题标题】:How to include nested and sibling associations in active record to_json?如何在活动记录 to_json 中包含嵌套和兄弟关联?
【发布时间】:2011-07-19 22:53:14
【问题描述】:

我有一个 Course 模型,它与另一个模型 Tree 有 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"

我阅读了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

这里的正确语法是什么?

【问题讨论】:

    标签: ruby-on-rails json activerecord


    【解决方案1】:

    你真的很亲密。只需使用哈希表示法而不是数组。

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

    【讨论】:

    • 后记:通常混合数组和哈希表示法似乎是个坏主意。但是,如果您转换为所有哈希,则有一个问题,如果一个兄弟关联有一个包含而一个没有,则不需要成为空哈希的道具的那个,如下所示: {:include=> { :tree_node=> {}, :definitions=> {}, :edit_lists=> {:include=> :edits}}}。
    • 谢谢!!!很丑但是很管用,你有没有找到任何可以让它更漂亮的宝石?
    • 如果递归无穷无尽怎么办?有没有办法在不明确指定 n 嵌套哈希的情况下将其遍历到最后一片叶子? PS:嗨,Ogz。
    • @Midwire 嘿!我不认为使用 Rails 的 JSON 支持来做你想做的事是不可能的。环顾四周,如果我错了,请告诉我。首先想到的是在您想要包含的每个模型上创建一个自定义 to_json 方法。
    • 这里有一个简单的例子来说明我的意思:gist.github.com/1499154。似乎应该已经有一些东西可以为你做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    相关资源
    最近更新 更多