ActsAsRelation 项目技术文档
1. 安装指南
在 Rails 4 中安装 ActsAsRelation,需要在 Gemfile 中添加以下代码:
gem 'acts_as_relation', '~> 1.0'
然后执行以下命令进行安装:
$ bundle install
如果是使用 Rails 3,需要在 Gemfile 中使用版本指定符 ~> 0.1。
2. 项目的使用说明
ActsAsRelation gem 用于实现多表继承(MTI)方法到 ActiveRecord 模型中。默认情况下,ActiveRecord 只支持单表继承(STI)。MTI 提供了 STI 的好处,但无需在单个表中放置数十个空字段。
以传统电子商务应用为例,一个产品有公共属性(如 +name+、+price+、+image+ 等),而每种产品类型有其自己的属性,例如 +pen+ 有 +color+ 属性,+book+ 有 +author+ 和 +publisher+ 属性。
使用 ActsAsRelation,可以按照以下方式声明模型:
class Product < ActiveRecord::Base
acts_as_superclass
end
class Pen < ActiveRecord::Base
acts_as :product
end
class Book < ActiveRecord::Base
acts_as :product
end
class Store < ActiveRecord::Base
has_many :products
end
在声明超级类的模型中,需要声明一个外键列和一个类型列。可以通过在 create_table 方法中设置 :as_relation_superclass 选项来实现:
create_table :products, :as_relation_superclass => true do |t|
# ...
end
或者在 polymorphic belongs_to 关系中声明,此时需要传递名称到 acts_as 和 acts_as_superclass 的 :as 选项。
接下来可以为 Product 类添加一些验证和方法:
class Product
validates_presence_of :name, :price
def to_s
"#{name} $#{price}"
end
end
现在可以像下面这样使用:
Pen.create :name => "Nice Pen", :price => 1.3, :color => "Red"
Pen.where "name = ?", "Some Pen"
pen = Pen.new
pen.valid? # => false
pen.errors.keys # => [:name, :price]
Pen.first.to_s # => "Nice Pen $1.3"
声明 acts_as 关系后,声明类会自动获得父类方法(包括访问器),可以直接访问它们。
还可以通过调用 specific 方法从父类中访问特定对象:
Product.first.specific # 将返回一个特定产品,例如一支笔
在 has_many 情况下,可以使用子类:
store = Store.create
store.products << Pen.create
store.products.first # => <Pen: ...>
3. 项目API使用文档
acts_as 关系支持以下选项:
:as:auto_join(默认为true):class_name:dependent
当 :auto_join 选项设置为 true 时,对子类的每次查询都会自动连接父表。
其他选项与 has_one 选项相同。
注意,":conditions" 和 ":include" 的支持已被移除,可以用 where() 和 includes() 替代。
例如:
acts_as :product, -> { where(color: "yellow") }
acts_as :person, -> { includes(:friends) }
4. 项目安装方式
请参考上述安装指南进行项目安装。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0137- DDeepSeek-V4-ProDeepSeek-V4-Pro(总参数 1.6 万亿,激活 49B)面向复杂推理和高级编程任务,在代码竞赛、数学推理、Agent 工作流等场景表现优异,性能接近国际前沿闭源模型。Python00
GLM-5.1GLM-5.1是智谱迄今最智能的旗舰模型,也是目前全球最强的开源模型。GLM-5.1大大提高了代码能力,在完成长程任务方面提升尤为显著。和此前分钟级交互的模型不同,它能够在一次任务中独立、持续工作超过8小时,期间自主规划、执行、自我进化,最终交付完整的工程级成果。Jinja00
MiniCPM-V-4.6这是 MiniCPM-V 系列有史以来效率与性能平衡最佳的模型。它以仅 1.3B 的参数规模,实现了性能与效率的双重突破,在全球同尺寸模型中登顶,全面超越了阿里 Qwen3.5-0.8B 与谷歌 Gemma4-E2B-it。Jinja00
MiniMax-M2.7MiniMax-M2.7 是我们首个深度参与自身进化过程的模型。M2.7 具备构建复杂智能体应用框架的能力,能够借助智能体团队、复杂技能以及动态工具搜索,完成高度精细的生产力任务。Python00
MusicFreeDesktop插件化、定制化、无广告的免费音乐播放器TypeScript00