When you serialize and de-serialize an object, the has_many :through relationships don't work.
p = Post.last
json = p.to_json
p2 = Post.new( JSON.parse(json) )
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
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.
id = p.id
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.
Post.new( JSON.parse(json) )
This issue has been automatically marked as stale because it has not been commented on for at least
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.
This issue has been automatically closed because of inactivity.