Ruby-on-rails 如何添加到序列化数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19134235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:48:20  来源:igfitidea点击:

How to add to a serialized array

ruby-on-railsrubyserialization

提问by grabury

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

In the controller I've tried

在我试过的控制器中

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

but I get the following error:

但我收到以下错误:

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

In my schema I have:

在我的架构中,我有:

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

Any ideas on where I'm going wrong?

关于我哪里出错的任何想法?

回答by Stefan

You can pass a class to serialize:

您可以将一个类传递给serialize

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

The above ensures that recent_messagesis an Array:

以上确保recent_messages是一个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.

请注意,如果类型不匹配,您可能必须转换现有字段。

回答by Hymanbot

It's because the first time you try to push an item to your recent_messages, there's no array to push the item into (the field is nilby default). So you must create the array before you can push to it

这是因为第一次尝试将项目推送到您的 时recent_messages,没有将项目推送到的数组(nil默认情况下该字段是)。所以你必须先创建数组,然后才能推送到它

@user = current_user
if @user.recent_messages.nil?
  @user.recent_messages = [params[:message]]
else
  @user.recent_messages << params[:message]
end
@user.save

回答by techvineet

You can also try following code:- By default @user.recent_messageswould be nil

您也可以尝试以下代码:- 默认情况下@user.recent_messages为 nil

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