Eager Load Depending on Type of Association in Ruby on Rails

后端 未结 7 2353
温柔的废话
温柔的废话 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条回答
  •  情歌与酒
    2021-02-07 22:33

    I've come up with a viable solution for myself when I was stuck in this problem. What I followed was to iterate through each type of implementations and concatenate it into an array.

    To start with it, we will first note down what attributes will be loaded for a particular type.

    ATTRIBS = {
      'Order' => [:address],
      'Customer' => [:location]
    }.freeze
    
    AVAILABLE_TYPES = %w(Order Customer).freeze
    

    The above lists out the associations to load eagerly for the available implementation types.

    Now in our code, we will simply iterate through AVAILABLE_TYPES and then load the required associations.

    issues = []
    
    AVAILABLE_TYPES.each do |type|
      issues += @issues.where(resource_type: type).includes(resource: ATTRIBS[type])
    end
    

    Through this, we have a managed way to preload the associations based on the type. If you've another type, just add it to the AVAILABLE_TYPES, and the attributes to ATTRIBS, and you'll be done.

提交回复
热议问题