0

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?

HJW
  • 342
  • 3
  • 13
  • The question does not make sense. What is the polymorphic association even supposted to accomplish if you have foreign key columns pointing to `memberships` and `tickets` anyways? And by "make sure that Rails raises an error" do you want to raise an exception or add a validation error? – max Oct 26 '21 at 21:21
  • It is polymorphic @max, the answer is below. – HJW Oct 28 '21 at 17:49

1 Answers1

0

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
    
XavM
  • 863
  • 9
  • 22