Ruby: Outputting Sequel model associations

∥☆過路亽.° 提交于 2019-12-23 05:23:58

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/23369336/ruby-outputting-sequel-model-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!