如何添加到序列化数组 [英] How to add to a serialized array

查看:34
本文介绍了如何添加到序列化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有用户,它有一个序列化字段,我希望能够将最近的消息添加到数组/序列化字段中.

I have an existing user which has a serialized field and I want to be able to add recent messages to the array / serialized field.

class User < ActiveRecord::Base
 serialize :recent_messages
end

在我尝试过的控制器中

@user = current_user
@user.recent_messages << params[:message]
@user.save

但我收到以下错误:

NoMethodError (undefined method `<<' for nil:NilClass):

在我的架构中,我有:

create_table "users", :force => true do |t|
    t.text     "recent_messages"
  end

对我哪里出错有什么想法吗?

Any ideas on where I'm going wrong?

推荐答案

您可以将类传递给 序列化:

You can pass a class to serialize:

class User < ActiveRecord::Base
  serialize :recent_messages, Array
end

以上确保 recent_messages 是一个 Array:

The above ensures that recent_messages is an Array:

User.new
#=> #<User id: nil, recent_messages: [], created_at: nil, updated_at: nil>

请注意,如果类型不匹配,您可能需要转换现有字段.

Note that you might have to convert existing fields if the types don't match.

这篇关于如何添加到序列化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆