之前在使用 Spree 這個電商模板的 gem 時,裡面有一個功能讓我覺得很方便
它是 preference,但看了一下原來是 serialize 幫你做的事情。

但今天的主角是 ActiveRecord::Store
store 其實也是 serialize 包裹著。

但總有些場景不想建欄位,卻又必須存些什麼。
例如 user 的一些基本設定?
在工作上時一直覺得 spreepreference 很好用。
可以用來存一些 key, value 的東西
剛好在今天查到了 store

其實 storeserialize 不一樣的地方。
應該在於 storeaccessors 可以直接 call key

首先我們要有一個欄位型態是 text

1
2
3
4
5
class UserAddTextTypeColumn < ActiveRecord::Migration[6.1]
def change
add_column :users, :settings, :text
end
end

接下來才在 Model設定

1
2
3
4
# serialize
class User < ApplicationRecord
serialize :settings
end

使用 serialize 需要透過以下的方法才能得到 value
console

1
2
3
4
# store
class User < ApplicationRecord
store :settings, accessors: :gender # accessors 可以設定我們的 keys
end

使用 store 則可以直接 call gender
console

總結:

  1. 在 store, user 這樣需要很多設定的時候, 這種序列化的功能或許會有幫助(?
  2. 相對的要下 SQL 語法查詢時也需要使用序列化的語法

ActiveRecord::Store API