Ruby:输出续集模型关联

时间:2014-04-29 15:45:02

标签: ruby-on-rails ruby postgresql-9.2 sequel

我认为只使用Sequel模型是可能的,但我想做的是让我的父模型(作者)输出其子模型( Book < / strong>)当我做Author.to_json之类的事情。这是我的代码:

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
  }]
}]

这正是我希望我的输出看起来的样子,但我对它的看法是值得怀疑的。理想情况下,如果作者模型上已有某些功能允许我这样做,那就太棒了......因为我不想实现 get_model < / strong>具有不同关联的所有模型的功能。另外,我希望NestedAttributes可以在这里伸出援助之手,但它看起来并不像。

我对Ruby和续集非常陌生,所以我想知道是否有更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

Sequel的json_serializer插件已通过:include选项支持关联。此外,您需要修复您的关联。这样的事情应该有效:

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