I'm having trouble with a named scope, SQL not my strong suit.
I would like to return ALL Machines which had it's LAST test fail.
My Machines model:
has_many :lodged_tests, :dependent => :destroy
has_one :last_test, :class_name => 'LodgedTest', :order => 'created_at DESC'
named_scope :last_test_failed, :joins => :last_test, :conditions => [ "lodged_tests.is_passed = ?", false]
The named_scope does work except it returns Machines which have ANY failed tests. I need it to return machines which only the most recent(LAST) test failed.
Below is link to a quick diagram of what i'm trying to do.
any help would be great thanks.
I have figured out how to achieve the desired result using SQL, not very rails like but it gets the job done.
needed to include the limit of 1 in a subselect in the conditions.
If anyone knows how to do this query using rails scope functions, I would be very interested to see an example.
This related S.O. question put me on the right path: tricky named scope in RoR