awesome-print / awesome_print

Pretty print your Ruby objects with style -- in full color and with proper indentation
http://github.com/michaeldv/awesome_print
MIT License
4.07k stars 454 forks source link

has_many :through relationship arrays always return empty #331

Closed Chadh13 closed 6 years ago

Chadh13 commented 6 years ago

Attempting to access arrays of associated objects that are created with has_many :through relationships always seem to return an empty array in awesome_print 1.8.0.

I was experiencing the issue specifically when using a Rails 5.0 accessor that is created thru reflection via a has_many through: relationship which is supposed to return an array of associated objects.

It appears that this was broken in this commit https://github.com/awesome-print/awesome_print/commit/04141b3cf586828494e352aa000d0bc321b5d7d1, and to be fair, it looks like @waldyr may have been misled by this typo https://github.com/rails/rails/commit/68d35960f336d5be3c5e35c88e6c8bdebcbcf500 😁

Downgrading to 'awesome_print', '1.7.0' temporarily resolves this incompatibility issue. I've submitted https://github.com/awesome-print/awesome_print/pull/332 to have it patched in 1.8.0 and above.

Example Models

class Physician < ApplicationRecord  
  has_many :appointments  
  has_many :patients, through: :appointments
end 

class Appointment < ApplicationRecord  
  belongs_to :physician
  belongs_to :patient
end 

class Patient < ApplicationRecord  
  has_many :appointments  
  has_one :physician, through: :appointments
end

Console Results

[1] pry(main)> Physician.find(1).patients
  Physician Load (0.5ms)  SELECT  "physicians".* FROM "physicians" WHERE "physicians"."id" = $1 LIMIT $2  [["id", 148], ["LIMIT", 1]]
[]

[2] pry(main)> Physician.find(1).patients.empty?
  Physician Load (0.5ms)  SELECT  "physicians".* FROM "physicians" WHERE "physicians"."id" = $1 LIMIT $2  [["id", 148], ["LIMIT", 1]]
true

[3] pry(main)> p = Physician.find(1).patients
...

[4] pry(main)> p.empty?
false

[5] pry(main)> Physician.find(1).patients.size
0

[6] pry(main)> Physician.find(1).patients.count
96

[7] pry(main)> Physician.find(1).patients.empty?
true

[8] pry(main)> Physician.find(1).patients.length.zero?
false
imajes commented 6 years ago

Thanks for the fix!