Rails: Best practice to store user settings?

Viewed 11799

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

5 Answers

Rails 6 supports ActiveRecordStore that can be used to solve this problem. The gem that improves ActiveRecordStore, by adding type definition, is activerecord-typedstore.

Define attributes in your model:

class User < ApplicationRecord
  typed_store :settings do |s|
    s.boolean :public, default: false, null: false
    s.string :email
    s.datetime :publish_at
    s.integer :age, null: false
  end
end

And use can use it:

shop = Shop.new(email: 'george@cyclim.se')
shop.public?        # => false
shop.email          # => 'george@cyclim.se'
shop.published_at   # => nil
Related