views:

78

answers:

2

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  A: 

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 }
jdeseno
I like your answer I'm just having a hard time getting it to save the array to the column now.
Joseph Silvashy
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.)
jdeseno
+2  A: 

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

Lolindrath