views:

561

answers:

3

Hi,

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

+4  A: 

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.

Jonathan Julian
+2  A: 

We use the helpful plugin called HasEasy. It stores the data in a vertical table, but allows you to add validations, pre/post storage processing, types, etc.

ScottD
That sounds interesting, but the link you posted is dead. Also Google didn't help. Any hints on where to find the plugin?
ole_berlin
link works for me
DanSingerman
strange, I get a "Page doesn't exist" on http://github.com/cjbottaro/has_easy
ole_berlin
ahhh, with www. it works: http://www.github.com/cjbottaro/has_easy
ole_berlin
Ok, I have no clue why the link doesn't work the first time. You refresh the page after you get the page not found and it goes right to it.
ScottD
perfect. I already love it!
ole_berlin
+3  A: 

If the user settings are not meant to be findable (via a User.find_by_x_preference, e.g.) you could also store 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#), actually.

class User < ActiveRecord::Base
  serialize :preferences
end

u = User.new
u.preferences = {:favorite_color => "green", :favorite_book => "Moby Dick"}
bantic