Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Keep has_many :through relationships when serializing to JSON and back in Rails 4.0.3 #14249

Closed
starrychloe opened this Issue · 3 comments

3 participants

@starrychloe

When you serialize and de-serialize an object, the has_many :through relationships don't work.

p = Post.last
p.tags
p.tags.count
json = p.to_json

p2 = Post.new( JSON.parse(json) )
p2.tags
p2.tags.count   ## Gives incorrect count

from_json doesn't work either. :include doesn't work either.

See more here: http://stackoverflow.com/questions/22106143/how-do-i-keep-has-many-through-relationships-when-serializing-to-json-and-back

@Alwahsh

p.to_json actually doesn't preserve the tags in the output json. If you do p2.tags you get the tags only because they are mapped in this database to the post with id = p.id and p2 has the same id as p. If you save p2 after giving it another id given that you've called p2.tags at least once before changing the id(To make it fetch the tags from the database that map to the old id), new tags are added that are mapped to the new p2 with its new id. When you call p2.tags.count then, it returns the correct number.
This wouldn't work if you're trying to add the post to another database though.

The reasonable suggestion would be to do it like this(as suggested in stackoverflow question):

Post.new.from_json p.to_json(include: :tags)

but it seems like Post.new( JSON.parse(json) ) doesn't convert the hash that represents the Tag to a Tag.
I'm wondering if the behaviour should be edited so that it would create a Tag from the hash.

@rails-bot rails-bot added the stale label
@rails-bot
Collaborator

This issue has been automatically marked as stale because it has not been commented on for at least
three months.

The resources of the Rails team are limited, and so we are asking for your help.

If you can still reproduce this error on the 4-1-stable, 4-0-stable branches or on master,
please reply with all of the information you have about it in order to keep the issue open.

Thank you for all your contributions.

@rails-bot rails-bot closed this
@rails-bot
Collaborator

This issue has been automatically closed because of inactivity.

If you can still reproduce this error on the 4-1-stable, 4-0-stable branches or on master,
please reply with all of the information you have about it in order to keep the issue open.

Thank you for all your contributions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.