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中的更新内容以及任何替代它的猴子补丁。
答案 0 :(得分:1)
最新版本的ActiveRecord使用关联中的基类,因此,当我们使用STI时,它将采用基类而不是当前类。
因此,您可以使用宝石404
来解决此问题。
它将使用ActiveRecord关联中的当前类。
这是github链接