Marcus
Marcus

Reputation: 9472

Rails Array set to "0" after save

I have built an array attribute into my model @users. I did this in the model user.rb serialize :year, Array.

I have a show page in my controller that first prints the @user and then changes the @user.year. It finishes by saving the @user.year.

The first time through when it prints @user.year it returns a [] to show that the array is empty. I print the array right before saving and it is populated with integers, but when I reload the next page the @user.year has switched from a [] to a 0. Any idea why this is?

:year is an assessable attribute in the @user model.

def show
@user = User.find(params[:id])
p "print @user"
p @user
...
@user.today_steps = day['summary']['steps']
@user.year.unshift(@user.today_steps)
...
p @user.year
  if @user.save(validate: false)
    p "Updated"
  else 
    p "Failed to Update"
  end
end
end

The @today_steps does save and is shown in the next call, but year doesn't. Any idea why this is?

Upvotes: 0

Views: 117

Answers (1)

BM5k
BM5k

Reputation: 1230

In order for serialize :year, Array to work, the year attribute needs to be a string.

Serialize stores the data in the database as yaml[1].

However, since your column type is integer, the yaml is being converted to an integer before being persisted to the database. Because of the way ruby converts strings to integers, 0 is the expected value given a yaml input.

y = [1,2,3].to_yaml # => "---\n- 1\n- 2\n- 3\n" 
y.to_i              # => 0

[1]: unless the class you specify implements load and dump

Upvotes: 1

Related Questions