I have seen two different approaches in saving user preferences.
APPROACH 1: Serializing them and saving in one of the column of USERS table
APPROACH 2: Creating a separate table PREFERENCES and make a has_many association from USERS to PREFERENCES.
Which one of the above two approaches would you prefer and what are the pros and cons of each over other?
I'd approach 2 because it is cleaner and easier to update. You will be able to add more preferences as complex as you want.
It will be a bit slower since you have a join to do, but it'll be worth it
There are some Rails plugins to handle this usecase:
It's usually a good idea to favor normalization. The second solution keeps your models cleaner, allows for easy extensibility if new preferences are added, and keeps your tables uncluttered.
An improved version of the first approach can be had if you're on PostgreSQL 9.2/3+ and Rails 4+. You can use
store_accessor
to store preferences in a PostgreSQL hstore column with support for validations and querying.user.receive_newsletter => 'true'
User.where("preferences->'receive_newsletter' = 'true'")
See http://mikecoutermarsh.com/using-hstore-with-rails-4/ for more details (migrations) and a special note on handling booleans.
Approach 2
You can add preferences, without cluttering up the user table
In 2016, I would back Option 2.
Why?
Read more