Ruby:输出续集模型关联

我不认为只使用Sequel模型是可能的,但我想做的是让我的父模型( 作者 )在我做Author.to_json这样的事情时输出它的子模型( Book )。 这是我的代码:

 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 

我的输出看起来像这样:

 [{ "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 }] }] 

这正是我希望我的输出看起来的样子,但我正在进行的方式是值得怀疑的。 理想情况下,如果作者模型上已经有一些function允许我这样做,那就太棒了……因为我不想为所有具有不同关联的模型实现get_model函数。 另外,我希望NestedAttributes可以在这里伸出援助之手,但它看起来并不像。

我是Ruby和Sequel的新手,所以我想知道是否有更简单的方法吗?

Sequel的json_serializer插件已经通过:include选项支持关联。 此外,您需要修复您的关联。 像这样的东西应该工作:

 Author.one_to_many :books Author.order(:id).to_json(:include=>:books)