Why polymorphic association doesn't work for STI if type column of the polymorphic association doesn't point to the base model of STI?

前端 未结 7 2036
旧时难觅i
旧时难觅i 2020-12-02 12:07

I have a case of polymorphic association and STI here.

# app/models/car.rb
class Car < ActiveRecord::Base
  belongs_to :borrowable, :polymorphic => tru         


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 13:01

    An older question, but the issue in Rails 4 still remains. Another option is to dynamically create/overwrite the _type method with a concern. This would be useful if your app uses multiple polymorphic associations with STI and you want to keep the logic in one place.

    This concern will grab all polymorphic associations and ensure that the record is always saved using the base class.

    # models/concerns/single_table_polymorphic.rb
    module SingleTablePolymorphic
      extend ActiveSupport::Concern
    
      included do
        self.reflect_on_all_associations.select{|a| a.options[:polymorphic]}.map(&:name).each do |name|
          define_method "#{name.to_s}_type=" do |class_name|
            super(class_name.constantize.base_class.name)
          end
        end
      end
    end
    

    Then just include it in your model:

    class Car < ActiveRecord::Base
      belongs_to :borrowable, :polymorphic => true
      include SingleTablePolymorphic
    end
    

提交回复
热议问题