Ordering Matters
So I found another interesting gotcha in Rails today.
Some background: I have a reporting application that uses models from a running application that I can’t touch the code for for fear of the FDA overlords. In doing some of the reports, I want to “fix” things that were left out of the original application. For instance the office model should be associated with the patients that belong to it; however, this is not the case.
Knowing the fun of “monkey patching”, I can easily add this association in my action on the reporting app with something like:
Office.class_eval("has_many :patients")
Now office.patients works.
Then I wanted to have the count of patients for each office so I used the same trick to have a variable to stuff the count in, ala:
Office.class_eval("attr_accessor :patient_count")
Now office.patient_count = office.patients.count works like a charm.
Here’s where the gotcha occurred. I was actually putting a condition on the count.
offices.each do |o|
o.patient_count = o.patients.count(1, :conditions => {:var => 'blah'})
end
I noticed later that the conditions were being ignored. Odd…
Here was the problem. I had the attr_accessor class_eval statement before the has_many class_eval. For some reason the order matters. Switching the two made things happy.