ruby-on-rails-5 - 使用 STI 时 Rails 5.0 不获取多态关联
问题描述
gem 'rails', '4.2.7.1'
class Property < Accommodation
has_many :attachments, as: :attached_item, dependent: :destroy
end
class Accommodation < ActiveRecord::Base;
end
class Attachment < ActiveRecord::Base
belongs_to :attached_item, polymorphic: true
end
该协会在 Rails 4.2 中运行良好
Property.last.attachments
Property Load (0.9ms) SELECT "accommodations".* FROM "accommodations" WHERE "accommodations"."type" IN ('Property') ORDER BY "accommodations"."id" DESC LIMIT 1
Attachment Load (0.5ms) SELECT "attachments".* FROM "attachments" WHERE "attachments"."attached_item_id" = $1 AND "attachments"."attached_item_type" = $2 [["attached_item_id", 1], ["attached_item_type", "Property"]]
Rails 5.0 中的类似关联
class CustomInquiry < ApplicationRecord;
end
class ChildInquiry < CustomInquiry
has_many :text_histories, as: :mailed_item, dependent: :delete_all
end
class TextHistory < ApplicationRecord
belongs_to :mailed_item, polymorphic: true
end
2.4.0 :002 > ChildInquiry.last.text_histories
ChildInquiry Load (1.2ms) SELECT "custom_inquiries".* FROM "custom_inquiries" WHERE "custom_inquiries"."type" IN ('ChildInquiry') ORDER BY "custom_inquiries"."id" DESC LIMIT $1 [["LIMIT", 1]]
TextHistory Load (0.4ms) SELECT "text_histories".* FROM "text_histories" WHERE "text_histories"."mailed_item_id" = $1 AND "text_histories"."mailed_item_type" = $2 [["mailed_item_id", 197], ["mailed_item_type", "CustomInquiry"]]
但是这里的第二个查询应该像 -
TextHistory Load (0.4ms) SELECT "text_histories".* FROM "text_histories" WHERE "text_histories"."mailed_item_id" = $1 AND "text_histories"."mailed_item_type" = $2 [["mailed_item_id", 197], ["mailed_item_type", "ChildInquiry"]]
任何人都可以帮助我解决 Rails 5 中更新的内容以及任何猴子补丁来覆盖它。
解决方案
最新版本的 ActiveRecord 在关联中使用基类,所以当我们使用 STI 时,它使用基类而不是当前类。因此,为了解决这个问题,您可以使用 Gem gem "store_base_sti_class"
。
它将使用 ActiveRecord 关联中的当前类。
这是github链接
推荐阅读
- python - 如何在同一张图表中同时绘制价格和交易量
- php - 树层次结构渲染 symfony 4
- python - 如何获得每个字母的协调并在 numpy 数组中提取字母?
- python - 从列表和数据透视表创建数据框,Python 3.6
- android - Android 语音通话中的语音转文本
- c# - 根据子类调度协变列表元素
- sql-server - 删除重复但保留多个
- azure-service-fabric - API 管理服务:如何导入 Service Fabric 集群 API?
- reactjs - Reactjs 组件层次结构可视化(树形视图)
- java - 即使在 Kafka 中进行轮询后,也不会发生当前的分区分配