On Friday, February 21, 2014 2:52:36 PM UTC-8, Kelly Dunn wrote:
>
> Hello there!
>
> I'm having some difficulty understanding how to serialize nested records
> in sequel. After reading the documentation, it seems that I might be able
> to serialize a nested data model like so:
>
> Class Foo
> one_to_many :bars
>
> plugin :json_serializer, {
> :include => {
> :bars => {
> :include => {
> :baz => {}
> }
> }
> }
> }
> end
>
> Class Bar
> one_to_one :baz
> end
>
> Class Baz
> end
>
> However, after calling Foo.new.to_json, and creating the associating
> records, I am returned a rather odd representation of JSON:
>
> {"id" => 1, :bars => [{"json"
> =>"{\"id\":1,\"baz\":{\"json\":\"{\\\"id\\\"}}}}]}
>
> As you can see, the Foo object (the root object) appears to render its
> attributes correctly, but the nested attributes not only have an
> undesirable "json" root key for their representation, but it also appears
> as they are being rendered as their stringified representation.
>
> Is this expected? Am I missing something?
>
> The sequel version I'm using is: 4.7.0
>
You need to load the json_serializer plugin in every model class that will
be serialized. In general, there shouldn't be harm in loading it directly
into Sequel::Model. Here's an example that works for me:
DB.create_table!(:foos){primary_key :id}
DB.create_table!(:bars){primary_key :id; Integer :foo_id}
DB.create_table!(:bazs){primary_key :id; Integer :bar_id}
Sequel::Model.plugin :json_serializer
class Foo < Sequel::Model
one_to_many :bars
plugin :json_serializer, :include=>{:bars=>{:include=>{:baz=>{}}}}
end
class Bar < Sequel::Model
one_to_one :baz
end
class Baz < Sequel::Model
end
f = Foo.create
f.add_bar({}).baz = Baz.create
puts Foo.first.to_json
{"id":1,"bars":[{"id":1,"foo_id":1,"baz":{"id":1,"bar_id":1}}]}
Thanks,
Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/groups/opt_out.