Rails 7 - ActiveRecord::Associations::Preloader.new.preload

ali*_*kht 8 ruby-on-rails-6 ruby-on-rails-7

考虑这段代码:

# in Rails 6.1
def preload(resource, relations)
  ActiveRecord::Associations::Preloader.new.preload(resource, relations)
end
Run Code Online (Sandbox Code Playgroud)

所以:我想改变它以与 Rails 7 兼容,所以我写了这个:

def preload(resource, relations)
  ActiveRecord::Associations::Preloader.new(records: resource, associations: relations)
end
Run Code Online (Sandbox Code Playgroud)

我做对了吗?因为 .preload(resource,relations) 在 Rails 7 中不再存在。如果您有任何其他建议,我非常期待

Rus*_*eev 13

你快到了。看起来这样有效:

    ActiveRecord::Associations::Preloader.new(
      records: [resource].flatten, # in case if resource is a single ApplicationRecord object
      associations: relations
    ).call
Run Code Online (Sandbox Code Playgroud)