jeudi 31 mars 2022

How can fix n+1 issue using associated values in rails?

I have those 3 tables in a relatiohship and i'm trying to speed up performance.

3 models (transformer, customer, customer_details )

Table transformers (id, name, customer_id). Table customers (id, name)- Table customer_details (id, name,customer_id)

Transformer.rb
 belongs_to :customer

Customer.rb
  has_many :transformers
  has_many :customer_details

CustomerDetail.rb
  belongs_to :customer

Here is the controller

@customers = Customer.include(:customer,:customer_detail).all

Here is the view

<% @transformers.each do |transformer| %>
  <%= transformer.name %>
  <%= transformer.customer.name %>
  <%= transformer.customer.customer_detail.name %>
<% end %>

Here is the log displayed:

  ↳ app/views/transformers/partials/_table.html.erb:20
  Customer Load (0.2ms)  SELECT "customers".* FROM "customers" WHERE "customers"."id" IN (?, ?, ?)  [["id", 1], ["id", 2], ["id", 3]]
  ↳ app/views/transformers/partials/_table.html.erb:20
  CustomerDetail Load (0.2ms)  SELECT "customer_details".* FROM "customer_details" WHERE "customer_details"."id" IN (?, ?, ?)  [["id", 1], ["id", 2], ["id", 3]]
  ↳ app/views/transformers/partials/_table.html.erb:20
  CustomerDetail Load (0.2ms)  SELECT "customer_details".* FROM "customer_details" WHERE "customer_details"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/views/transformers/partials/_table.html.erb:27
  CustomerDetail Load (0.2ms)  SELECT "customer_details".* FROM "customer_details" WHERE "customer_details"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  ↳ app/views/transformers/partials/_table.html.erb:27
  CustomerDetail Load (0.1ms)  SELECT "customer_details".* FROM "customer_details" WHERE "customer_details"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]

The result should

  ↳ app/views/transformers/partials/_table.html.erb:20
  Customer Load (0.2ms)  SELECT "customers".* FROM "customers" WHERE "customers"."id" IN (?, ?, ?)  [["id", 1], ["id", 2], ["id", 3]]
  ↳ app/views/transformers/partials/_table.html.erb:20
  CustomerDetail Load (0.2ms)  SELECT "customer_details".* FROM "customer_details" WHERE "customer_details"."id" IN (?, ?, ?)  [["id", 1], ["id", 2], ["id", 3]]

I tried but is a wrong code.

@customers = Customer.include(:customer,:customer_details).all

Aucun commentaire:

Enregistrer un commentaire