Question

I don't think this is possible using just Sequel models, but what I would like to do is have my parent model (Author) output its child model (Book) when I do something like Author.to_json. Here is my code:

require 'sequel'
require 'json'

db = Sequel.connect('postgres://localhost/testing');

class Sequel::Model
  self.plugin :json_serializer
end

class Author < Sequel::Model(:author)
  one_to_many :book, key: :author_id, primary_key: :id

  def get_author
    Author.each do |e|
      books = Array.new
      e.book.each do |f|
        books.push(f.values)
      end
      e.values[:books] = books
      puts JSON.pretty_generate(e.values)
    end
  end
end

class Book < Sequel::Model(:book)
end

author = Author.new
author.get_author

My output looks something like this:

[{
  "id": 1,
  "name": "Jack Johnson",
  "books": [{
    "id": 4,
    "name": "Songs with Chords",
    "genre": "Learning",
    "author_id": 1
  }]
}, {
  "id": 2,
  "name": "Mulder",
  "books": [{
    "id": 2,
    "name": "UFOs",
    "genre": "Mystery",
    "author_id": 2
  }, {
    "id": 3,
    "name": "Unexplained Paranorma",
    "genre": "Suspense",
    "author_id": 2
  }]
}, {
  "id": 3,
  "name": "Michael Crichton",
  "books": [{
    "id": 1,
    "name": "Jurassic Park",
    "genre": "Incredible",
    "author_id": 3
  }]
}]

That's exactly how I want my output to look, but the way I'm going about it is questionable. Ideally, if there's some function already on the Author model that allows me to do this, that'd be awesome... as I don't want to have to implement a get_model function for all of my models that have different associations. Also, I was hoping NestedAttributes could lend a hand here, but it doesn't look like it.

I'm very new to Ruby and Sequel, so I'd like to know if there's a simpler way of doing this?

Was it helpful?

Solution

Sequel's json_serializer plugin already has support for associations via the :include option. Also, you need to fix your association. Something like this should work:

Author.one_to_many :books
Author.order(:id).to_json(:include=>:books)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top