SuperAPI AI 工具集

store-model-coder

数据与分析

查看项目

更新于 10-16 00:03

技能介绍

用途:用 store_model 把基于 JSON 的数据库列包装成类似 ActiveModel 的类,从而获得类型安全、验证和清晰的职责分离。适合带验证字段的配置对象、存放在 JSON 列中的嵌套属性、需要类型安全与 ActiveModel 行为的 JSON 数据,以及希望把 JSON 逻辑与父 ActiveRecord 模型分离的场景。

主要能力:通过 include StoreModel::Model 定义类,用 attribute 声明类型(如 :string、:integer、:float)及默认值,并可使用 validates 与 enum。在 ActiveRecord 中用 attribute :configuration, Configuration.to_type 注册;数组用 LineItem.to_array_type。支持嵌套模型(如 Coordinate.to_type)、枚举及其谓词与方法(如 active?、active!)、默认值、以及通过 store_model: { merge_errors: true } 或 merge_array_errors: true 把子对象验证错误合并到父模型,错误消息形如 "Address street can't be blank"。可接受哈希或 StoreModel 实例赋值。

使用方式:在 Gemfile 加入 gem "store_model", "~> 3.0"。控制器中按普通参数白名单放行嵌套键,例如 params.require(:product).permit(:name, configuration: [:model, :color, :max_speed, :status])。测试可用 RSpec 直接验证 validate、enum 与错误合并行为。

限制:StoreModel 不会自动检测嵌套改动,需重新赋值整个对象、调用 configuration_will_change!,或以属性哈希整体赋值。若只是简单键值设置,宜用 ActiveRecord::Store 或 store_accessor;需要数据库级 JSON 查询宜用 PostgreSQL jsonb 运算符;数据需要关系或连接时应规范化为独立表;无需验证的简单 JSON 直接访问列即可。