ActiveRecord通过针对STI类的作用域构建错误类的实例 [英] ActiveRecord builds instance of wrong class through a scope targeting an STI class
问题描述
我希望能够在通过STI类型定位到特定模型类的作用域上调用build
方法,并让ActiveRecord构建正确类的实例.
I would like to be able to call the build
method on a scope that targets a certain class of model via its STI type, and have ActiveRecord build an instance of the correct class.
class LineItem < ActiveRecord::Base
scope :discount, where(type: 'DiscountLineItem')
end
class DiscountLineItem < LineItem; end
> LineItem.discount.build # Expect an instance of DiscountLineItem here
=> #<LineItem ...>
在这里,我期望的是DiscountLineItem
的实例,而不是LineItem
的实例.
Here, I expected an instance of DiscountLineItem
, not an instance of LineItem
.
推荐答案
即使ActiveRecord不会将对象实例化为正确的类,它也会正确设置类型.基本上,您有两种解决方法:
Even though ActiveRecord doesn't instantiate the object as the right class, it does set the type correctly. You basically have two ways around this:
1)创建对象,然后从数据库中重新加载它:
1) Create the object and then reload it from the database:
item = LineItem.discount.create(attrs...)
item = LineItem.find(item.id)
2)使用STI类并直接从其构建对象:
2) Use the STI class and build the object directly from it:
DiscountLineItem.build
ActiveRecord可以做的所有事情,这似乎是一种毫无意义的限制,并且可能很难改变.现在,您激起了我的兴趣:)
With all that ActiveRecord can do, this does seem like kind of a senseless limitation and might not be too hard to change. Now you've piqued my interested :)
更新:
这最近被添加到Rails 4.0 中,并带有以下提交消息:
This was recently added to Rails 4.0 with the following commit message:
允许您执行BaseClass.new(:type =>"SubClass")以及 parent.children.build(:type =>"SubClass")或parent.build_child 初始化STI子类.确保类名是有效的 阶级是在超阶级的祖先中 协会在期待.
Allows you to do BaseClass.new(:type => "SubClass") as well as parent.children.build(:type => "SubClass") or parent.build_child to initialize an STI subclass. Ensures that the class name is a valid class and that it is in the ancestors of the super class that the association is expecting.
这篇关于ActiveRecord通过针对STI类的作用域构建错误类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!