オームモデルツリーをJSON構造に変換します
-
12-10-2019 - |
質問
オームモデルの木があります。ゲームにはプレイヤーがいて、プレイヤーにはピースがあります。詳細については、以下のとおりです。基本的に、構造をJSONとしてレンダリングすると、エンコードエラーが表示されます。
nomethoderror(#piece:0x00000102b8dbb8の未定義の方法 `encode_json '):
ただし、エラーなしでプレーヤーとそのピースを出力できます。
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
解決
これが問題を中心に機能することがわかりました。
class Player < Ohm::Model
def to_hash
super.merge(:name => name, :pieces => pieces.all)
end
end
所属していません StackOverflow