Rails: Best practice to store user settings?

Ole Spaarmann picture Ole Spaarmann · Nov 5, 2009 · Viewed 10.8k times · Source

I'm wondering what the best way is to store user settings? For a web 2.0 app I want users to be able to select certain settings. At the moment is it only when to receive email notifications.

The easiest way would be to just create a Model "Settings" and have a column for every setting and then have a 1-1 relationship with users.

But is there a pattern to solve this better? Is it maybe better to store the info in the user table itself? Or should I use a table with "settings_name" and "settings_value" to be completely open about the type of settings stored there (without having to run any migrations when adding options)?

What is your opinion?

Thanks

Answer

joaomilho picture joaomilho · Aug 12, 2013

If you use PostgreSQL, the best solution is to use https://github.com/diogob/activerecord-postgres-hstore/. It's a simple, fast and reliable way to store hashes in the database. Since it's not just a serialised text field, you can search on it also, and you don't need to create a new table, as in HasEasy.

def User
  serialize :preferences, ActiveRecord::Coders::Hstore
end

user = User.create preferences: { theme: "navy" }
user.preferences['theme']