2012-12-18 54 views
0

我有一個錯誤的軌道,從 「的ActiveSupport :: JSON:編碼:: CircularReferenceError」,activerecord循環引用錯誤究竟意味着什麼?你如何解決它?

我不知道完全當它說我有一個對象引用自身的錯誤意味着什麼。有人可以解釋一下,並幫助我理解如何解決它?

錯誤來自以下代碼。 在我的模型,稱之爲

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

    def self.search_wines(params) 
     scope = self 
     [:wineries,:varietals,:wines].each do |s| 

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

,這是從我的控制器叫我打電話

 
return_wines = Wine.search_wines({wineries:wineries,varietals:varietals,wines:wines}) 
     render :json => return_wines.to_json(:include=>[:winery,:varietals]) 

回答

1

這通常意味着要打印其JSON模型包括自身的模型,通常是通過另一種模式。

E.g.考慮這兩個類

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. 
      } 
     ] 
     } 
    } 
    ] 
]} 
相關問題