ghe*_*ton 7 ruby activerecord ruby-on-rails ruby-on-rails-3
我正在处理一个已经有一个具有自然类型名称的列的表.例如,已经存在一个名为"provider"的列,其值为"foo"或"bar".我想使用现有的类型名称在此表上使用STI ,因为为Active Record添加一个名为"type"的附加列似乎很愚蠢.问题是,这些类型名称与ruby类完全不匹配.我希望能够设置自定义映射,例如Class1 => foo,Class2 => bar.
我尝试了以下方法:
# In the base class
set_inheritance_column :provider
# In Class1
def self.sti_name
'foo'
end
# In Class2
def self.sti_name
'bar'
end
Run Code Online (Sandbox Code Playgroud)
但这似乎没有削减它,我得到:
The single-table inheritance mechanism failed to locate the subclass: 'foo'
...
activerecord (3.0.8) lib/active_record/base.rb:923:in `find_sti_class'
Run Code Online (Sandbox Code Playgroud)
看起来ActiveRecord只能处理完整的类名和解密的类名.我不确定具有受保护的sti_name方法的目的是什么.
我将深入挖掘框架并覆盖ActiveRecord :: Base.compute_type.在我这样做之前,有没有人这样做过?这是一场疯狂的追逐吗?
rails可以处理自定义类型名称还是我坚持使用Ruby类名称?
更新
我得到了这个:
# In the base class
def self.find_sti_class(type_name)
# Do mapping from foo/bar to Class1/Class2
...
end
Run Code Online (Sandbox Code Playgroud)
我仍然担心会遇到更多问题.这是正确的方法吗?
查看 AR 代码并只关注sti_name和instantiate..似乎对您来说修补这两种方法就足够了。
我没有这方面的经验,但它看起来并不复杂。看起来是这样instantiate的:
def instantiate(record)
model = find_sti_class(record[inheritance_column]).allocate
model.init_with('attributes' => record)
model
end
Run Code Online (Sandbox Code Playgroud)
理想情况下,您希望扫描代码以查找引用类似record[inheritance_column]或简单内容的任何内容inheritance_column,然后在其中注入您自己的映射代码。粗略浏览了一下,似乎很多地方都没有使用它。
我想说你正在尝试的事情是可能的:),但是你将需要基本实例化的测试用例+涉及关联的东西,以确保 AR 可以找到并为不同的情况构建正确的 SQL。
很明显,AR 并不是按照您想要的方式构建的,因为inheritance_column代码中的使用并未在任何地方明确抽象出来。这就是为什么您需要更多地研究代码。
| 归档时间: |
|
| 查看次数: |
2213 次 |
| 最近记录: |