Rails:检查多态关系中关联的belongs_to对象类型

Rails: Check associated belongs_to object type in a polymorphic relation

我有三个模型:

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

比如说,我有一个 product,它有一个关联的 membership。例如。我可以这样做:product.membershipproduct.object

但在这种情况下我也可以做到 product.ticket

如何确保 Rails 在这种情况下引发错误?

您可能应该看一下 this post,其中引用了一些针对此问题的解决方案。 也许 也能帮到你。

这些帖子中列出的解决方案:

  • 上Rails5.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
    
  • 在 Rails 4.2 上(但在 6.1 上似乎已弃用,因为不再允许 foreign_type

    belongs_to :membership, -> { where(notes: { object_type: :Membership }) }, foreign_key: :object_id, foreign_type: :Membership, optional: true
    
  • 上 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