12

I have somewhat of a unique situation, if I had a form with a checkbox for every state (as in US states, so 50 states say), I don't really want to add 50 columns to my db, how can I store them in an array in a single column?

I feel like I've seen this done but I'm having a hard time putting my finger on the implementation.

1
  • You could use states * ';' and states.split ';', and make sure semicolons don't appear in states. Commented Jul 26, 2014 at 12:52

2 Answers 2

21

ActiveRecord::Base.serialize. Straight from the rails docs:

class User < ActiveRecord::Base
  serialize :preferences
end

user = User.create(:preferences => { "background" => "black", "display" => large })
User.find(user.id).preferences # => { "background" => "black", "display" => large }
Sign up to request clarification or add additional context in comments.

2 Comments

I like your answer I'm just having a hard time getting it to save the array to the column now.
If you're using an existing column, you may need to change the column type to :text to fit your array. (Check your_a.to_yaml.length.)
4

You could set up a States table with many to many relationship between User and State also. This would make queries more efficient.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.