Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 989
JP Silvashy Avatar asked Aug 14 '10 17:08

JP Silvashy


People also ask

Can I store array in database?

An array is a special variable that allows storing one or more values in a single variable e.g. – holding usernames or details in an Array. They are easier to manipulate. Sometimes, require to store Array in the MySQL database and retrieve it.

Does Ruby on Rails have a database?

Rails comes with built-in support for SQLite, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.

Can you store an array in an array?

We can create such a memory representation by using an array of arrays. There are two fundamental ways by which to create two dimensional arrays in LiveCode: 1. First create a number of arrays that each stores one dimensional data, then store these arrays in a new array to create the second dimension.


1 Answers

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 }
like image 199
jdeseno Avatar answered Sep 17 '22 14:09

jdeseno