开发者

Converting Ohm model tree into a JSON structure

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜