ruby-on-rails - ActiveRecord 通过针对 STI 类的范围构建错误类的实例

标签 ruby-on-rails scope polymorphic-associations arel sti

我希望能够在通过 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/

相关文章:

ruby-on-rails - 考虑使用现有数据(不是数据库,实际数据)的新 Rails 应用程序——最好的处理方法是什么?

java - 将实体字段更改为不同类型的字段

ruby-on-rails - 通过多态关联 rails 创建对象

ruby-on-rails - STI 和多晶型物

c++ - 将 C++ lambda 复制到函数指针引用

javascript - 了解 jQuery 中更改事件中 'this' 的范围

ruby-on-rails - 设计不在注册/编辑中保存密码更改

ruby-on-rails - capistrano 的部署问题

ruby-on-rails - 在 Ruby on Rails 中选择查询

angular - fullcalendar Angular - 更新 eventDrop 和 eventResize 上的数据库