0

我目前有一个范围,我正在尝试查找在关联中创建的最后一条记录,如果特定的布尔值为 false,则选择它

IE Foo has_many Bar's 和 Bar's 有一个名为 bazzed 的布尔列

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

这个问题是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

问题在于 rails 在 where 子句之后调用 order 和 limit,我正在寻找的是先执行 order 和 limit 以尝试找到最后一个设置为 false 的 bar。

是否有本地 AR 方式来执行我试图完成的查询?

编辑

我试图抓住有一个 bar 的 foo,其中最后一个 bar 设置为 false 并且只有当 foo 的最后一个 bar 有 false bazzed 时。

4

2 回答 2

1

Ok, I would suggest this for the query on the "foo" model:

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.

[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. 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.

于 2012-04-30T15:46:09.357 回答
0

现在使用类方法,但问题在于它返回一个数组对象,而不是我想要返回的活动记录关系。仍在尝试正确完成查询。

于 2012-05-01T19:05:26.767 回答