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.
Here are the two options. 1. NoSQL database. 2. Rails 4 Store feature.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With