mtcrts70
mtcrts70

Reputation: 35

Rails Convert YAML In Database To Array In Controller

I have an array of integers that gets stored in my DB as yaml. I'm looking for a way to convert the yaml back to an array in my controller.

Here is the migration:

class AddRandomExerciseArrayToUsers < ActiveRecord::Migration
  def change
    add_column :users, serialize :random_exercise_array, :text
  end
end

Here is what it looks like in the DB:

random_exercise_array: "---\n- 1\n- 2\n- 3\n- 5\n- 1\n- 0\n- 1\n- 2\n- 1\n- 4\n">

In the above instance how could I get an array of integers as follows [1,2,3,5,1,0,1,2,1,4] back into my controller?

Edit:

Relevant controller code:

def index   
    if current_user.bookmark2 == 0 && current_user.random_exercise_array.nil?
      exerciseArray = Array.new(10) 

      for i in 0..9
        exerciseArray[i] = rand(0..5)
      end

      current_user.random_exercise_array = exerciseArray
      current_user.save
    end 
end

Upvotes: 0

Views: 427

Answers (1)

pangpang
pangpang

Reputation: 8821

You can get useful information from this link(http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html)

If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, then specify the name of that attribute using this method and it will be handled automatically. The serialization is done through YAML.

class AddRandomExerciseArrayToUsers < ActiveRecord::Migration
  def change
      add_column :resources, :random_exercise_array, :text
  end
end

then run: rake db:migrate

class User < ActiveRecord::Base
    serialize :random_exercise_array #add this line to your user model
end

If you store an array in DB, you can get an array directly and doesn't need to handle it by yourself.

Upvotes: 1

Related Questions