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 2037
旧时难觅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:53

    I agree with the general comments that this ought to be easier. That said, here is what worked for me.

    I have a model with Firm as the base class and Customer and Prospect as the STI classes, as so:

    class Firm
    end
    
    class Customer < Firm
    end
    
    class Prospect < Firm
    end
    

    I also have a polymorphic class, Opportunity, which looks like this:

    class Opportunity
      belongs_to :opportunistic, polymorphic: true
    end
    

    I want to refer to opportunities as either

    customer.opportunities
    

    or

    prospect.opportunities
    

    To do that I changed the models as follows.

    class Firm
      has_many opportunities, as: :opportunistic
    end
    
    class Opportunity
      belongs_to :customer, class_name: 'Firm', foreign_key: :opportunistic_id
      belongs_to :prospect, class_name: 'Firm', foreign_key: :opportunistic_id
    end
    

    I save opportunities with an opportunistic_type of 'Firm' (the base class) and the respective customer or prospect id as the opportunistic_id.

    Now I can get customer.opportunities and prospect.opportunities exactly as I want.

提交回复
热议问题