Eager Load Depending on Type of Association in Ruby on Rails

后端 未结 7 2439
温柔的废话
温柔的废话 2021-02-07 22:13

I have a polymorphic association (belongs_to :resource, polymorphic: true) where resource can be a variety of different models. To simplify the questio

7条回答
  •  猫巷女王i
    2021-02-07 22:41

    You can break out your polymorphic association into individual associations. I have followed this and been extremely pleased at how it has simplified my applications.

    class Issue
      belongs_to :order
      belongs_to :customer
    
      # You should validate that one and only one of order and customer is present.
    
      def resource
        order || customer
      end
    end
    
    Issue.preload(order: :address, customer: :location)
    

    I have actually written a gem which wraps up this pattern so that the syntax becomes

    class Issue
      has_owner :order, :customer, as: :resource
    end
    

    and sets up the associations and validations appropriately. Unfortunately that implementation is not open or public. However, it is not difficult to do yourself.

提交回复
热议问题