Best approach to save user preferences?

2019-01-16 10:07发布

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?

7条回答
看我几分像从前
2楼-- · 2019-01-16 10:44

I grappled with this same question so I thought I'd share what I found in a "community wiki" answer.

Serializing in a single attribute

Simple user preferences for your Rails app is a blog post describing how to do this.

Edit a serialized hash in a form? describes how to edit such a hash in a form. A helpful trick is to make the form from OpenStruct.new(@user.preferences) hash to automatically make accessor methods for each hash attribute.

DYE/has_serialized - GitHub lets you treat those attributes in the serialized hash as attributes on the (user) model.

Preferences in a separate table

Best practice to store user settings? has some tips. Below are some libs including two from another answer by @hopeless.

  • rails-settings manages a table of key/value pairs like a Hash stored in you database, using simple ActiveRecord like methods for manipulation. You can store any kind of object: Strings, numbers, arrays, or any object which can be noted as YAML. (Tested with Rails 3.1 and newer including Rails 4.x and Rails 5.x)
  • Preference-fu is good for simple boolean preferences, uses a single column for multiple preferences.(last updated 2009)
  • Preferences is more flexible, uses a separate table, some nice syntactic sugar. (last updated 2011)
  • HasEasy stores the data in a vertical table, but allows you to add validations, pre/post storage processing, types, etc. (Last updated 2008)

You can also try using metaprogramming: Practical Metaprogramming with Ruby: Storing Preferences

查看更多
登录 后发表回答