John
John

Reputation: 23

Rails serializing cannot insert value

I created migration

add_column :users, :read_post_id, :integer

Added to the user model

serialize :read_post_id  , Array

Edit: if I use

<%=  User.find(current_user.id).read_post_id << 3 %>

I get an output [3]. But this value is only temporary and is not saved. How to save it ? I read Rails serialized integer attribute in params, but not saving into model instance which says serialized attributes cannot be integer. Changed it to text. After

<%=  User.find(current_user.id).read_post_id << ["3","5"] %>
<%=  User.find(current_user.id).read_post_id.count %>
<%=  User.find(current_user.id).save %>

I do receive an ouput [["3", "5"]] 0 true

So basicly nothing has changed

Upvotes: 0

Views: 38

Answers (1)

e_a_o
e_a_o

Reputation: 601

You will need to change the data type of read_post_id column to :text instead of :integer.

Why? Because Active Record serializes any object in text columns using YAML, not integer columns. The serialized data need to go into a text column not integer column. See AR doc: Saving arrays, hashes, and other non-mappable objects in text columns

To change the column type, create a new migration file that looks like this:

class ChangeReadPostIdColumnType < ActiveRecord::Migration
  def change
    change_column :users, :read_post_id, :text
  end
end

A quick unsolicited suggestion, if read_post_id is going to be serialized into an array of ids, why don't you name it read_post_ids for easy readability?

You can use the snippet below to change the column name and the column type in one migration file:

class ChangeReadPostIdColumnNameAndType < ActiveRecord::Migration
  def change
    change_column :users, :read_post_id, :text
    rename_column :users, :read_post_id, :read_post_ids
  end
end

Upvotes: 1

Related Questions