开发者

Rails - serialize another activerecord model

开发者 https://www.devze.com 2023-01-21 21:21 出处:网络
I\'m looking to serialize an incomplete/temporary model as an attribute of another model such as: class User < ActiveRecord::Base

I'm looking to serialize an incomplete/temporary model as an attribute of another model such as:

class User < ActiveRecord::Base
  serialize :pending_post
end

Where pending_post is assigned an activerecord model:

...
user.pending_post = Post.new(:title => "Whatever", :message => "whatever")
user.save

But instead of saving the yaml for the new Post model, the pending_post attribute is nil (in the DB and on reload). The serialize works great with other objects, Hashes, Arrays, etc, but comes up nil in this case. This is Rails 2.3.9, but I did a quick test with 3.0.1 and saw the same results. I found this description of the issue from years ago: http://www.ruby-forum.com/topic/101858.

I know I could manually serialize/deserialize the object (which works fine) or serialize just the post.attributes, but I'm curious if anyone knows why this acts as it does? It seems if the new post is saved before being assigned to user.pending_post, then just the ID is saved as the user.pending_post attribute. I'm pretty sure it's intentional and not a bug, but I quite don't开发者_如何转开发 understand the reasoning. Is it poor form to serialize an active_record model?


I think you need to serialize/save the attributes, not the post object itself, like so:

user.pending_post = {:title => 'Whatever', :message => 'whatever'}
user.save

Then later you can turn it into a real post:

user.posts.create user.pending_post

And I'd probably take it a step further (as I so often do) with a user method:

def save_post
  self.posts.create self.pending_post
end

I hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消