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:22

I'd approach 2 because it is cleaner and easier to update. You will be able to add more preferences as complex as you want.

It will be a bit slower since you have a join to do, but it'll be worth it

查看更多
何必那么认真
3楼-- · 2019-01-16 10:29

There are some Rails plugins to handle this usecase:

  • Preference-fu (good for simple boolean preferences, uses a single column for multiple preferences)
  • Preferences (more flexible, uses a separate table, some nice syntactic sugar)
查看更多
爷的心禁止访问
4楼-- · 2019-01-16 10:34

It's usually a good idea to favor normalization. The second solution keeps your models cleaner, allows for easy extensibility if new preferences are added, and keeps your tables uncluttered.

查看更多
仙女界的扛把子
5楼-- · 2019-01-16 10:35

An improved version of the first approach can be had if you're on PostgreSQL 9.2/3+ and Rails 4+. You can use store_accessor to store preferences in a PostgreSQL hstore column with support for validations and querying.

class User
  store_accessor :preferences, :receive_newsletter

  validates :receive_newsletter, presence: true
end

user.receive_newsletter => 'true'

User.where("preferences->'receive_newsletter' = 'true'")

See http://mikecoutermarsh.com/using-hstore-with-rails-4/ for more details (migrations) and a special note on handling booleans.

查看更多
可以哭但决不认输i
6楼-- · 2019-01-16 10:37

Approach 2

You can add preferences, without cluttering up the user table

查看更多
冷血范
7楼-- · 2019-01-16 10:41

In 2016, I would back Option 2.

Why?

User settings tend to become a core piece of every application. If they are retrieved on every request, you’re now making an extra query with each request. Using a separate table makes sense when you have to have individual columns for each setting. But since we’re using jsonb, that’s not an issue. It’s just a single column.

Read more

查看更多
登录 后发表回答