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?
关于我哪里出错的任何想法?
3 个解决方案
#1
50
You can pass a class to serialize
:
您可以传递一个类来序列化:
class User < ActiveRecord::Base
serialize :recent_messages, Array
end
The above ensures that recent_messages
is an Array
:
以上确保recent_messages是一个数组:
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.
请注意,如果类型不匹配,您可能必须转换现有字段。
#2
2
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 nil
by 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
#3
2
You can also try following code:- By default @user.recent_messages
would be nil
您还可以尝试以下代码: - 默认情况下,@ user.recent_messages将为零
@user.recent_messages ||= []
@user.recent_messages << params[:message]
@user.save
#1
50
You can pass a class to serialize
:
您可以传递一个类来序列化:
class User < ActiveRecord::Base
serialize :recent_messages, Array
end
The above ensures that recent_messages
is an Array
:
以上确保recent_messages是一个数组:
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.
请注意,如果类型不匹配,您可能必须转换现有字段。
#2
2
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 nil
by 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
#3
2
You can also try following code:- By default @user.recent_messages
would be nil
您还可以尝试以下代码: - 默认情况下,@ user.recent_messages将为零
@user.recent_messages ||= []
@user.recent_messages << params[:message]
@user.save