How to add to a serialized array

后端 未结 3 2013
名媛妹妹
名媛妹妹 2020-12-13 18:18

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 < ActiveReco         


        
相关标签:
3条回答
  • 2020-12-13 18:31

    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
    
    0 讨论(0)
  • 2020-12-13 18:33

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

    @user.recent_messages ||= []
    @user.recent_messages << params[:message]
    @user.save
    
    0 讨论(0)
  • 2020-12-13 18:45

    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.

    0 讨论(0)
提交回复
热议问题