简体   繁体   English

Rails 3.2并让AR正确排序此查询

[英]Rails 3.2 and getting AR to properly order this query

I currently have a scope where I am attempting to find last record created in an association and select it if a particular boolean value is false 我目前在一个范围内尝试查找在关联中创建的最后一条记录,如果特定的布尔值是false,则选择它

IE Foo has_many Bar's and Bar's has a boolean column named bazzed IE Foo has_many Bar's and Bar's有一个名为bazzed的布尔列

scope :no_baz,   joins(:bars).order("bars.id DESC").limit(1).where("bars.bazzed = 'f'")

The problem with this is that rails turns this query into something like this 问题是,Rails将查询转换为类似的内容

SELECT "foos".* FROM "foos" INNER JOIN "bars" ON "bars"."foo_id" = "foos"."id" WHERE (bars.bazzed = 'f') ORDER BY bars.id DESC LIMIT 1

the problem lies that rails is calling the order and limit after the where clause, what i'm looking for is to do the order and limit first to try and find the last bar that has bazzed set to false. 问题在于,rails在where子句之后调用了order and limit,我要寻找的是先执行order and limit尝试找到最后被设置为false的小节。

Is there a native AR way to perform the query I am attempting to accomplish? 是否有本机AR方法来执行我尝试完成的查询?

EDIT 编辑

I am trying to grab the foo's that have a bar where the last bar they have has bazzed set to false and only if the last bar that that foo has has a false bazzed. 我试图抓住具有小节的foo,只有当该foo的最后一个小节被设置为false时,才将它们设置为false的最后一个小节设置为false。

Ok, I would suggest this for the query on the "foo" model: 好的,对于“ foo”模型的查询,我建议这样做:

Foo.bars.where("bars.bazzed = ?", 'f').all( :order => "created_at DESC").first

Note: 'f' can be replaced by false, depending on the value you use in your "bazzed" column, of course. 注意:当然,“ f”可以用false代替,具体取决于您在“ bazzed”列中使用的值。

[Edit] [编辑]

Ok, as I think I better understand the problem, here is a suggestion, but for a public method and not a scoped query. 好的,我认为我可以更好地理解问题,这是一个建议,但针对的是公共方法而不是范围查询。

def no_baz
  all_no_baz_foos = Array.new
  Foo.all.each do |foo|
      last_bar = foo.bars.all.order("bars.id DESC").first
      if last_bar.bazzed == 'f'
        all_no_baz_foos << foo
      end
  end
  return all_no_baz_foos
end

This method will return an Array with all the no_baz_foos record in it. 此方法将返回其中包含所有no_baz_foos记录的Array。 As I did not test my code, you may have to change few things for it to work, but I think you get the idea. 由于我没有测试我的代码,因此您可能必须进行一些更改才能使其正常工作,但是我认为您已经明白了。

For the "scope" method, I just can't find a way to chain correctly the queries to have the desired result. 对于“范围”方法,我只是找不到一种方法来正确地链接查询以得到所需的结果。 If anyone else knows how to achieve that using a scope, I'll be glad to hear the solution too. 如果其他人知道如何使用示波器实现这一目标,我也会很高兴听到解决方案。

Using a class method for now but the problem with that lies that it returns an array object and not an active record relation which is what i'm trying to return. 现在使用类方法,但是问题在于它返回一个数组对象,而不是我要返回的活动记录关系。 Still attempting to get the query correctly done. 仍在尝试正确完成查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM