用途:为 Rails 模型定义正确、可维护且高性能的 Active Record 关联,并排查关联相关错误。
主要能力:判断关联类型(一对一、一对多、多对多、多态、自关联);编写对应迁移(t.references、foreign_key: true、唯一索引、NOT NULL);为 has_many/has_one 设置 dependent:(:destroy、:delete_all、:nullify、:restrict_with_error、:destroy_async);用 includes/preload/eager_load/strict_loading 消除 N+1;在需要时指定 inverse_of;配置 counter_cache、scoped 关联与排序;调试关联(reflect_on_all_associations、to_sql、查找孤儿记录、reset_counters)。
使用方式:先确定关系类型,外键位于 belongs_to 一侧;检查现有代码与迁移约定;编写模型关联与迁移;为每个 has_many/has_one 设置 dependent:;按需预加载;必要时补 inverse_of。常用命令:rg "has_many|has_one|belongs_to|has_and_belongs_to_many" app/models/;rg "add_reference|t.belongs_to|t.references|foreign_key" db/migrate/。
适用场景:新建或修改模型关系、创建外键与连接表迁移、修复 N+1、搭建多态或自关联、在 has_many :through 与 HABTM 之间选择、添加计数器缓存、排查关联报错。
限制与注意:关联不会自动创建数据库列,必须写迁移;多对多优先 has_many :through 而非 HABTM;多态外键无法使用数据库级外键约束,仅 2-3 个模型时不宜使用;belongs_to 默认校验存在性,仅在允许 NULL 时用 optional: true;不要给 belongs_to 设置 dependent:;大集合避免 dependent: :destroy,可考虑 :delete_all 或 :destroy_async。具体版本要求与更多细节暂未提供。