我希望能够在通过 STI 类型针对特定模型类的作用域上调用 build
方法,并让 ActiveRecord 构建正确类的实例。
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
的实例。
最佳答案
尽管 ActiveRecord 没有将对象实例化为正确的类,但它确实正确设置了类型。基本上有两种方法可以解决这个问题:
1)创建对象,然后从数据库重新加载它:
item = LineItem.discount.create(attrs...)
item = LineItem.find(item.id)
2) 使用 STI 类并直接从中构建对象:
DiscountLineItem.build
就 ActiveRecord 的所有功能而言,这似乎是一种毫无意义的限制,而且可能并不难改变。现在你引起了我的兴趣:)
更新:
这是最近的added to Rails 4.0包含以下提交消息:
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.
关于ruby-on-rails - ActiveRecord 通过针对 STI 类的范围构建错误类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11387836/