将欧姆模型树转换为JSON结构

时间:2011-01-18 06:38:09

标签: ruby-on-rails ruby json redis ohm

我有一个欧姆模型树。游戏有玩家,玩家有玩家。详情如下。基本上,当我将结构渲染为json时,我看到编码错误:

  

NoMethodError(#Piece的未定义方法`encode_json':0x00000102b8dbb8):

但是,我可以输出播放器及其片段,没有错误。

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)    

我最好的猜测是,在集合的嵌套中存在导致此问题的问题。

有什么想法吗?

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

1 个答案:

答案 0 :(得分:2)

我发现这可以解决问题:

class Player < Ohm::Model
  def to_hash
    super.merge(:name => name, :pieces => pieces.all)
  end
end