【发布时间】:2014-04-02 02:28:57
【问题描述】:
如何转换为 JSON 并返回并保持关系?当我解包对象时,它认为它们不存在!
irb(main):106:0* p = Post.last
=> #<Post ...
irb(main):107:0> p.tags
=> #<ActiveRecord::Associations::CollectionProxy [#<Tag id: 41, ...
irb(main):109:0* p.tags.count
=> 2 #### !!!!!!!!!!!!
irb(main):110:0> json = p.to_json
=> "{\"id\":113,\"title\":... }"
irb(main):111:0> p2 = Post.new( JSON.parse(json) )
=> #<Post id: 113, title: ...
irb(main):112:0> p2.tags
=> #<ActiveRecord::Associations::CollectionProxy []>
irb(main):113:0> p2.tags.count
=> 0 #### !!!!!!!!!!!!
这是模型
class Post < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
有人建议,但没有用
irb(main):206:0* Post.new.from_json p.to_json(include: :tags)
ActiveRecord::AssociationTypeMismatch: Tag(#60747984) expected, got Hash(#15487524)
【问题讨论】:
-
你调用
p2 = Post.new( JSON.parse(json) )这不保存到数据库。并在您的数据库上调用p2.tags.count查询,但您不保存数据。 -
@Monk_Code 不,这仍然不起作用。另请参阅下面对答案的评论。
> p2 = Post.new( JSON.parse(json) )ActiveRecord::AssociationTypeMismatch: Tag(#62190408) expected, got Hash(#15487524)
标签: ruby-on-rails ruby json ruby-on-rails-4 redis