rails7: 网站的配置表 settings

每个网站的必备表,settings
更新于: 2023-12-13 23:48:25

需求

如果我想管理一个网站的配置。
我用一个 settings 表,怎么设计,考虑缓存,尽量用 rails g 命令

migration

生成数据表

rails generate model Setting key:string:index value:text
rails db:migrate

具体的 model

文件位置: app/models/setting.rb

  • 获取值
  • 并且将取得的值,尝试转化为 json
class Setting < ApplicationRecord
  validates :key, presence: true, uniqueness: true

  def self.get_value(key)
    Rails.cache.fetch("setting_#{key}") do
      setting = find_by(key: key)
      setting&.parsed_value
    end
  end

  def parsed_value
    JSON.parse(value) if value.present?
  rescue JSON::ParserError
    value
  end
end

去掉 updated_at/created_at

class Setting < ApplicationRecord
  validates :key, presence: true, uniqueness: true
  # ... 省略10000行代码
  def as_json(options = {})
    super(options.merge(except: [:created_at, :updated_at]))
  end
end

settings_controller

  • 注意 params.require(:setting).permit! 因为这里的 value 可能是 json,所以最好这么设置
  • 另一种方式: params.require(:setting).permit(:key, :value: [:name, :age])
### create
POST http://localhost:3000/backend/settings
Content-Type: application/json

{
  "key": "opts",
  "value": {"name":"aric","age":108}
}

### show
GET http://localhost:3000/backend/settings/opts
class Backend::SettingsController < Backend::BaseController
  def index
    wrap do
      @data = Setting.all
    end
  end

  def show
    wrap do
      @data = Setting.find_by(key: params[:id])
    end
  end

  def update
    wrap do
      @data = Setting.find_by(key: params[:id])
      @data.update!(setting_params)
    end
  end

  def create
    wrap do
      @data = Setting.create!(setting_params)
    end
  end

  private
  def setting_params
    Rails.logger.info params.inspect
    params.require(:setting).permit!
  end
end

参考