Rails: Best practice for storing custom settings?

I am wondering what is the best way to store user settings? For a Web 2.0 application, I want users to be able to choose specific settings. At the moment, this is only when to receive email notifications.

The easiest way is to simply create a “Settings” model and have a column for each parameter, and then have a 1-1 relationship with users.

But is there a sample to solve this better? Maybe it's better to store information in the user table itself? Or should I use a table with the parameters "settings_name" and "settings_value" to fully open the type of settings stored there (without the need to perform any migrations when adding options)?

What is your opinion?

thank

+22
ruby-on-rails settings user-controls
Nov 05 '09 at 17:06
source share
4 answers

We use a useful plugin called HasEasy . It stores data in a vertical table, but allows you to add checks, processing before / after storage, types, etc.

+5
Nov 05 '09 at 17:17
source share

If you use PostgreSQL, the best solution would be to use https://github.com/diogob/activerecord-postgres-hstore/ . This is a simple, fast and reliable way to store hashes in a database. Since this is not just a serialized text field, you can search on it as well, and you do not 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'] 
+12
Aug 12 '13 at 7:03 on
source share

The “open” table approach makes AR modeling difficult because you have to worry about data types (boolean, int, string, etc.). I always added prefs as columns in the users table, and then moved them to the user_preferences table if there are “too many” of them. It is simple and easy to work with.

+11
Nov 05 '09 at 17:14
source share

If user preferences are not intended to be searched (for example, through User.find_by_x_preference), you can also save them in a serialized column as a hash. This is the use case described in the rails docs ( http://www.railsbrain.com/api/rails-2.3.2/doc/index.html?a=M002334&name=serialize# ).

 class User < ActiveRecord::Base serialize :preferences end u = User.new u.preferences = {:favorite_color => "green", :favorite_book => "Moby Dick"} 
+10
Nov 05 '09 at 20:05
source share



All Articles