0

我从 rails "ActiveSupport::JSON::Encoding::CircularReferenceError" 得到一个错误,

当它说我有一个引用自身的对象时,我不确定该错误是什么意思。有人可以解释一下,并帮助我了解如何解决吗?

错误来自以下代码。在我的模型中,调用

范围 :search_wineries, lambda{|wineries|{:joins => :winery, :conditions =>["wineries.id IN (?)", wineries]}}
    范围 :search_varietals, lambda{|varietals|{:joins => :varietals, :conditions => ["varietals.id IN (?)",varietals] }}
    范围 :search_wines, lambda{|wines|{:conditions=>["wines.id IN (?)",wines]}}

    def self.search_wines(参数)
        范围=自我
        [:wineries,:varietals,:wines].each do |s|

            scope = scope.send("search_#{s}", params[s]) if !params[s].empty?
        结尾
        范围
    结尾

这是从我的控制器调用的

return_wines = Wine.search_wines({葡萄酒:葡萄酒,品种:品种,葡萄酒:葡萄酒})
        渲染 :json => return_wines.to_json(:include=>[:winery,:varietals])
4

1 回答 1

2

这通常意味着您正在打印一个其 json 模型包含自身的模型,通常是通过另一个模型。

例如考虑这两个类

class Pet
  belongs_to :owner

  def as_json
    super(only: :name, include: :owner)
  end
end

class Owner
  has_many :pets
  def as_json
    super(only: :name, include: :pets)
  end
end

我们可以将它们中的每一个打印为 json

o = Owner.new(name: "Steve")
o.as_json 
#=> { name: "Steve", pets: [] }

p = Pets.new(name: "Fido", owner: nil)
p.as_json 
#=> { name: "Fido", owner: nil } 

p.owner = o
o.as_json 
#=> FAILS with CircularReference error. Why?

想想它应该产生什么。

o.as_json 
#=>
{ 
  name: "Steve",
  pets: [
    {
      name: "Fido",
      owner: {
        name: "Steve", # Uh oh! We've started to repeat ourselves.
        pets: [
          {
             name: "Fido",
             owner: ...and so on, and so on, forever recursing, because the models json representation *includes* itself.
           }
         ]
       }
     }
   ]
]}
于 2013-12-13T05:15:01.837 回答