0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

6 Comments

You may have not seen my post edit, but I did the migration from integer to text and it is still not working @esther
@John okay, just seeing the updated posted. Can you use the = operator instead of the << operator? Also can you update the post to show the full console logs? Lastly, you can just make use of current_user.read_post_id instead of User.find(current_user.id).read_post_id
Tried = and it does same as <<. Also tried current_user - undefined method `read_post_id=' And probably this is the problem. Do I have to specify read_post_id somewhere else i.e in the controller ? @esther
@John Oh, have you tried updating the user object in the controller or model instead of in the views/erb file? <%= ideally should only be used for display. What does your current_user method look like? I assumed that this returns a user object?
def current_user login_from_session || login_from_basic_auth end @esther
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.