ruby-on-rails-5polymorphic-associationssti

Rails 5.0 not fetching polymorphic association when STI is used


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

The association works totally fine in 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"]]

Similar association in 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"]]

But here the second query should run like--

 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"]]

Can anyone help me with what is get updated in rails 5 and any monkey patch to override it.


Solution

  • Latest version of ActiveRecord uses the base class in the association, so when we use STI then it takes base class instead of current class. So for solving this you can use Gem gem "store_base_sti_class".
    It will use the current class in ActiveRecord association.
    Here is the github link

    https://github.com/appfolio/store_base_sti_class