Named Scope to only search first results of joined table

此生再无相见时 提交于 2019-12-11 06:31:15

问题


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.

Named Scope Diagram

any help would be great thanks.


回答1:


Have you tried to add a limit of 1?

named_scope :last_test_failed, :joins => :last_test, :conditions => [ "lodged_tests.is_passed = ?", false], :order => "created_at desc", :limit => 1



回答2:


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.

named_scope :last_test_failed, :conditions => ["(SELECT is_passed FROM lodged_tests WHERE lodged_tests.machine_id = machines.id ORDER BY created_at DESC LIMIT 1) = ?", false]

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



来源:https://stackoverflow.com/questions/4858646/named-scope-to-only-search-first-results-of-joined-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!