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 2019
旧时难觅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:08

    This is how I solved that problem using aforementioned hints:

    # app/models/concerns/belongs_to_single_table_polymorphic.rb
    
    module BelongsToSingleTablePolymorphic
      extend ActiveSupport::Concern
    
      included do
        def self.belongs_to_sti_polymorphic(model)
          class_eval "belongs_to :#{model}, polymorphic: true"
          class_eval 'before_validation :set_sti_object_type'
    
          define_method('set_sti_object_type') do
            sti_type = send(model).class.name
    
            send("#{model}_type=", sti_type)
          end
        end
      end
    end
    
    

    and with that, for any model in which I would find belongs_to :whatever, polymorphic: true I do:

    class Reservation < ActiveRecord::Base
      include BelongsToSingleTablePolymorphic
      # .....
      belongs_to_sti_polymorphic :whatever
      # .....
    end
    
    0 讨论(0)
提交回复
热议问题