1

I want to store an array into a database field. I tried the following method:

class MyStuff < ActiveRecord::Base  
  serialize :things
end

stuff = MyStuff.new 
stuff.things << "pen" 
stuff.things << "paper"
stuff.save

I get an error: "The error occurred while evaluating nil.<<"

Is there any other approach?

2 Answers 2

8

What is "things". Define it to be Array or Hash or something you want that to be and then add elements to it.

stuff = MyStuff.new 

stuff.things = []
stuff.things << "pen"
..

stuff.save
Sign up to request clarification or add additional context in comments.

1 Comment

Do I need to use serialize?
2

you can use this, this will work for existing things as well.

stuff.things ||= [] //without || your existing things will be reset
stuff.things << "pen"
..

1 Comment

Good point. With .new it doesn't matter, but with existing records, your answer will save many from deleting their data!

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.