Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to a serialized array

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?

like image 592
grabury Avatar asked Oct 02 '13 09:10

grabury


People also ask

What is a serialized array?

The serialize array function is a built-in function in PHP. The serialization of data means converts a value into a sequence of bits to be stored in a memory buffer, in a file, or transfer across a network.

What is the use of serialize ()?

The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.


3 Answers

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:

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.

like image 177
Stefan Avatar answered Oct 22 '22 08:10

Stefan


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

@user = current_user
if @user.recent_messages.nil?
  @user.recent_messages = [params[:message]]
else
  @user.recent_messages << params[:message]
end
@user.save
like image 2
jackbot Avatar answered Oct 22 '22 08:10

jackbot


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

@user.recent_messages ||= []
@user.recent_messages << params[:message]
@user.save
like image 2
techvineet Avatar answered Oct 22 '22 07:10

techvineet