mercredi 7 mars 2018

Loading Relations

Goal: I would like to include all of a customers medical conditions as an array in the result of a customer.

for:

cust = Customer.includes(:conditions).find(1)

expected result:

#<Customer id: 1, first_name: "John", last_name: "Doe", conditions [...]>

actual result:

#<Customer id: 1, first_name: "John", last_name: "Doe">

code:

I have 2 classes and a 3rd join class (ConditionsCustomer).

class Customer < ApplicationRecord
    has_many :conditions_customers
    has_many :conditions, through: :conditions_customers
end

#join table. Contains 2 foreign_keys (customer_id, condition_id)
class ConditionsCustomer < ApplicationRecord
  belongs_to :customer
  belongs_to :condition
end

class Condition < ApplicationRecord
  has_many :conditions_customers
  has_many :customers, through: :conditions_customers
end

What's interesting is that I see 3 select queries getting fired (customer, join table and medical conditions table) but then unfortunately the customer returns without the medical conditions.

I've also tried using a join but I get an array of same customer over and over again.

Is there an easy way to do this with ActiveRecord? I would prefer not having to merge the record manually.

Aucun commentaire:

Enregistrer un commentaire