Domanda

Ho un albero di modelli Ohm. Un gioco ha giocatori, un giocatore ha Pezzi. I dettagli completi sono qui di seguito. Fondamentalmente, quando vado a rendere la struttura come JSON, visualizzato un errore di codifica:

NoMethodError (metodo non definito `encode_json' per #Piece: 0x00000102b8dbb8):

Tuttavia, può emettere il Player e loro pezzi senza errori.

Player = Player.create(:name => "Toby")
game.player << player 

player.pieces << Piece.create(:name => "Rook")

# works fine 
logger.debug(player.to_hash.to_json)

# FAILS with the above error
logger.debug(game.to_hash.to_json)    

La mia ipotesi migliore è che ci sia qualcosa nella nidificazione delle collezioni che sta causando il problema qui.

Tutte le idee?

class Game < Ohm::Model
  collection :player, Player  

  def to_hash
    super.merge(:players => players)
  end
end


class Player < Ohm::Model
  reference :game, Game
  collection :pieces, Piece

  attribute :name  

  def to_hash
    super.merge(:name => name, :pieces => pieces)
  end
end


class Piece < Ohm::Model
  reference :player, Player

  def to_hash
    super.merge(:name => name)
  end    
end
È stato utile?

Soluzione

Ho trovato questo funziona il problema:

class Player < Ohm::Model
  def to_hash
    super.merge(:name => name, :pieces => pieces.all)
  end
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top