Eager Load Depending on Type of Association in Ruby on Rails

后端 未结 7 2341
温柔的废话
温柔的废话 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:20

    You can do that with the help of ActiveRecord::Associations::Preloader class. Here is the code:

    @issues = Issue.all # Or whatever query
    ActiveRecord::Associations::Preloader.new.preload(@issues.select { |i| i.resource_type == "Order" }, { resource: :address })
    ActiveRecord::Associations::Preloader.new.preload(@issues.select { |i| i.resource_type == "Customer" }, { resource: :location })
    

    You can use different approach when filtering the collection. For example, in my project I am using group_by

    groups = sale_items.group_by(&:item_type)
    groups.each do |type, items|
      conditions = case type
      when "Product" then :item
      when "Service" then { item: { service: [:group] } }
    end
    
    ActiveRecord::Associations::Preloader.new.preload(items, conditions)
    

    You can easily wrap this code in some helper class and use it in different parts of your app.

提交回复
热议问题