Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: dynamic columns/attributes on models?

I have a SaaS application, where accounts want to save different types of information on a User model. So for example, one account may want to save age, and birthdate, but in another account, they won't be using those columns and will want to save info on hair color, and height.

These are just examples, but how would I structure my model and db so that it works well with "customized, dynamic" columns without creating too many empty attributes.

like image 688
kibaekr Avatar asked Sep 25 '14 02:09

kibaekr


3 Answers

Here are the two options. 1. NoSQL database. 2. Rails 4 Store feature.

like image 171
Vijendra Avatar answered Oct 21 '22 20:10

Vijendra


To me this sound like a perfect example were you want to use a schema free NoSQL database.

Or (if you want to stick with SQL) you can have a base User model with a has_many :attributes association. In which a attribute is just a combination of a key ('age', 'birthday', 'hair color') and a value. Complexity comes with different datatypes and queries covering multiple attributes at the same time.

like image 22
spickermann Avatar answered Oct 21 '22 20:10

spickermann


If you're using Postgresql you can take a look at hstore then you can save the information serialized and actually you can make some queries against those hashes btw Rails 4 has included this feature but if you are using an older Rails version you can include this gem. https://github.com/diogob/activerecord-postgres-hstore in your Gemfile and you should be able to start playing like:

user = User.new
user.preferences = {
  email: "[email protected]",
  github: "heridev"
}

user.save!
user.reload

# Searching
User.where("preferences @> hstore(:key, :value)", key: "email", value: "[email protected]").first
like image 25
Heriberto Magaña Avatar answered Oct 21 '22 20:10

Heriberto Magaña