我有一棵欧姆模型树。游戏有玩家,玩家有棋子。完整的细节如下。基本上,当我将结构呈现为 json 时,我看到一个编码错误:
NoMethodError(#Piece:0x00000102b8dbb8 的未定义方法`encode_json'):
但是,我可以毫无错误地输出 Player 及其 Pieces。
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