Wednesday 15 May 2013

ruby - Return database results in the same JSON parent and children -



ruby - Return database results in the same JSON parent and children -

i have team , players classes , want homecoming info in 1 json string contains team info @ same time displays info players.

class team < activerecord::base has_many :players end class players < activerecord::base belongs_to :team end

i know how retrieve info team , players not in same query. problem don't how merge result jsons in 1 json.

team = team.last.to_json player = team.players.to_json

how can query info team , players in same query. tried:

@team = team.includes(:players).where(players: {team_id: team.last}).last.to_json

and returns me info team. want json like:

-id -name -players -player -player

in case it's impossible, how can merge 1 json info 2 queries.

you can write "join" incorporate players in team team information. @ point you'll have construction has info needed create json. see "12 joining tables" active record documentation more information.

or, can create 2 separate queries, create bit more complex json hash or array allowing output both sets of info 1 larger serialized object. instance:

require 'json' team = { 'name' => 'bears' } players = { '1' => 'fred', '2' => 'joe' } puts ({ 'team' => team, 'players' => players }).to_json

here's output:

{"team":{"name":"bears"},"players":{"1":"fred","2":"joe"}}

here's info returned ruby object:

data = '{"team":{"name":"bears"},"players":{"1":"fred","2":"joe"}}' json[data] # => {"team"=>{"name"=>"bears"}, "players"=>{"1"=>"fred", "2"=>"joe"}}

also, since you're using sinatra, it's not necessary utilize active record. sequel orm, , personal favorite when working sinatra. might find easier work with.

ruby json activerecord sinatra

No comments:

Post a Comment