命名范围只能搜索连接表的第一批成果 [英] Named Scope to only search first results of joined table
问题描述
我在使用了一个名为范围的麻烦,SQL不是我的强项。
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.
我的机器型号:
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]
在named_scope不只是它的工作返回具有任何失败的测试机。 我需要它返回的机器,只有最近的(最后一个)测试失败。
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.
推荐答案
我已经找到了如何使用SQL来达到预期的效果,不是很喜欢轨道,但它能够完成任务。
I have figured out how to achieve the desired result using SQL, not very rails like but it gets the job done.
需要包括1极限在条件子查询。
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]
如果任何人知道如何使用Rails范围函数来做到这一点查询,我会非常有兴趣看到一个例子。
If anyone knows how to do this query using rails scope functions, I would be very interested to see an example.
此相关S.O.问题把我在正确的道路上:<一href="http://stackoverflow.com/questions/4629077/converting-a-simple-query-into-a-tricky-named-scope-in-ror/4629552#4629552">tricky在回报率命名范围
This related S.O. question put me on the right path: tricky named scope in RoR
这篇关于命名范围只能搜索连接表的第一批成果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!