Retrieving nested records in Sequel Retrieving nested records in Sequel sqlite sqlite

Retrieving nested records in Sequel


Artist.eager(:albums).all does eagerly load the albums, but {|a| p a} is not going to show the albums (as Sequel::Model#inspect only shows values for the current model, not any associated objects). Use {|a| p [a, a.albums]} to see that the albums are already loaded.

If you want to produce the hash you described:

Artist.eager(:albums).all.map do |a|  a.values.merge(:albums=>a.albums.map{|al| al.values})end


You can add a method to Artist to output it the way you want it

class Artist < Sequel::Model(:artists)  one_to_many  :albums, :key => :artist_id  def my_hash    to_hash.merge!(        {            :albums => albums.map{|a|                 a.to_hash.reject!{ |k,v|                     k==:artist_id                }            }        }    )  endendclass Album < Sequel::Model(:albums)  many_to_one  :artist, :key => :artist_idendrecords = Artist.all.map{ |a| a.my_hash }p records

Instead of using reject! it would be cleaner to add a my_hash method the Album to return a hash without the :artist_id, but you get the idea. This outputs:

[  {    :albums=>[      {        :title=>"Only You",         :id=>1      },       {        :title=>"Only Us",         :id=>2      }    ],    :name=>"Mike",    :id=>1  },  {    :albums=>[      {        :title=>"Only Me",         :id=>3      }    ],     :name=>"John",     :id=>2  }]