Home > Net >  Rails: Check associated belongs_to object type in a polymorphic relation
Rails: Check associated belongs_to object type in a polymorphic relation

Time:10-29

I have three models:

class Product
  belongs_to :object, polymorphic: true
  belongs_to :membership, foreign_key: :object_id
  belongs_to :ticket, foreign_key: :object_id
end

class Membership
end

class Ticket
end

Say, I have a product that has an associated membership. E.g. I could do: product.membership or product.object

But in this case I could also do product.ticket.

How can I make sure that Rails raises an error in this case?

CodePudding user response:

You probably should take a look at this post which reference few solutions for this problem. Maybe this post could help you too.

Solutions listed on these posts :

  • On Rails 5.2

    belongs_to :membership, -> { includes(:object).where(products: { object_type: Membership.to_s }) }, foreign_key: :object_id
    belongs_to :ticket, -> { includes(:object).where(products: { object_type: Ticket.to_s }) }, foreign_key: :object_id
    
  • On Rails 4.2 (but seem deprecated on 6.1 because foreign_type is not allowed anymore)

    belongs_to :membership, -> { where(notes: { object_type: :Membership }) }, foreign_key: :object_id, foreign_type: :Membership, optional: true
    
  • On Rails 4.1

    class Product < ActiveRecord::Base
    # The true polymorphic association
    belongs_to :object, polymorphic: true
    
    # The trick to solve this problem
    has_one :self_ref, :class_name => self, :foreign_key => :id
    
    has_one :membership, :through => :self_ref, :source => :object, :source_type => Membership
    has_one :ticket, :through => :self_ref, :source => :object, :source_type => Ticket
    
  • Related