0

我有一个拥有许多商店的 Account 类。在 Store 类中,有一个例程返回该帐户的所有其他商店:

def other_stores
  if account then
    account.stores.find(:all,:conditions=>"id != "+id.to_s)
  else
    []
  end
end

当我在我的 as_json 例程中包含 :other_stores 然后引用它时,我固定一个 cpu 并挂起。我假设它是 other_stores 中的无限递归。有任何想法吗?有什么办法可以停止递归?

Ruby 1.9.2-p136,Rails 3.0.3

4

2 回答 2

0

它很可能看起来像这样,假设你有[@store1, @store2]

@store1.as_json
#as_json calls @store1.other_stores() ==> [@store2]
  @store2.as_json
  #as_json calls @store2.other_stores() ==> [@store1]
    @store1.as_json
    #calls @store1.other_stores() other_stores ==> [@store2]

最简单的解决方法是传入已经渲染的 id:

def as_json(rendered_ids = [])
于 2011-12-01T19:25:26.873 回答
0

我想我已经想通了。这似乎有效:

def as_json(options={}) 
  super(:methods => [:blah, :etc, 
                     :other_stores => {:except => :other_stores} ]) 
end 

克里斯

于 2011-12-02T16:45:12.993 回答