سؤال

I have a tree of Ohm models. A Game has Players, a Player has Pieces. The full details are below. Basically, when I go to render the structure as json, I see an encoding error:

NoMethodError (undefined method `encode_json' for #Piece:0x00000102b8dbb8):

However, I can output the Player and their Pieces with no error.

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)    

My best guess is that there is something in the nesting of the collections that is causing the problem here.

Any ideas?

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
هل كانت مفيدة؟

المحلول

I found this works around the problem:

class Player < Ohm::Model
  def to_hash
    super.merge(:name => name, :pieces => pieces.all)
  end
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top