Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Best practice to store user settings?

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

like image 219
Ole Spaarmann Avatar asked Nov 05 '09 17:11

Ole Spaarmann


2 Answers

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']
like image 65
joaomilho Avatar answered Nov 09 '22 11:11

joaomilho


The "open" table approach makes it difficult to model with AR, since you have to worry about the types of the data (boolean, int, string, etc). I've always added prefs as columns on the users table, and then move them out to a user_preferences table if there are "too many" of them. It's simple, and it's easy to work with.

like image 11
Jonathan Julian Avatar answered Nov 09 '22 12:11

Jonathan Julian