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 2042
旧时难觅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 12:42

    You can also build a custom scope for a has_* association for the polymorphic type:

    class Staff < ActiveRecord::Base
      has_one :car, 
              ->(s) { where(cars: { borrowable_type: s.class }, # defaults to base_class
              foreign_key: :borrowable_id,
              :dependent => :destroy
    end
    

    Since polymorphic joins use a composite foreign key (*_id and *_type) you need to specify the type clause with the correct value. The _id though should work with just the foreign_key declaration specifying the name of the polymorphic association.

    Because of the nature of polymorphism it can be frustrating to know what models are borrowables, since it could conceivably be any model in your Rails application. This relationship will need to be declared in any model where you want the cascade deletion on borrowable to be enforced.

提交回复
热议问题