JP Silvashy
JP Silvashy

Reputation: 48555

Storing an array in the database in ruby on rails

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.

Upvotes: 12

Views: 9179

Answers (2)

Lolindrath
Lolindrath

Reputation: 2101

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

Upvotes: 4

user324312
user324312

Reputation:

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 }

Upvotes: 21

Related Questions