Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

ruby on rails - Storing arrays in database using ActiveRecord

I am on rails 2.3.8 & I am using mysql as db adapter. I want to store arrays in my database. After searching I could come up with this very useful article.

Now I need to use GUI for input & not only server console. So say I have a text field called nums which logically should have int array. What should be the format of nums so that it becomes easy to retrieve & store the array out of that string ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you use serialize then you shouldn't have to worry about how the data is stored within the text field, although it's actually YAML.

serialize is documented in the Rails/ActiveRecord API (scroll down to the section headed "Saving arrays, hashes, and other non-mappable objects in text columns")

For display, you need a format that is understandable to users and that can be easily converted back into an array in your code. Comma- or space-delimited?

Formatting for output:

delim = ',' # or ' ' for spaces, or whatever you choose
array.join(delim)

Converting back into an array might work as follows:

num_array = nums.split(delim).map(&:to_i) # or to_f if not integers

or perhaps using String#scan?

num_array = nums.scan(/d+/).map(&:to_i) # for positive integers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...