转换一个简单的查询到RoR中一个棘手的命名范围 [英] Converting a simple query into a tricky named scope in RoR

查看:232
本文介绍了转换一个简单的查询到RoR中一个棘手的命名范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的作用域的问题。我想做到这一点作为一个范围:

I have a simple scoping question. I would like to do this as a scope:

if article.responses.blank?
      return false
elsif article.responses.last.passed.eql?(false)
      return true
else
   return false
end

于是在文章模型我有这样的事情:

So on the article model I would have something like this:

scope :failed_response, {
    :joins=>[:responses],
    :conditions=>["responses.passed = ?", false]
  }

现在的问题是,我只希望情况下的最新的的响应失败。我敢肯定,这是一种用任何花哨的排序或某种嵌套查询做到这一点,但我坚持。谢谢!

The problem is, I only want instances where the most recent response failed. I'm sure these is a way to do this with either fancy sorting or some kind of nested query, but I'm stuck. Thanks!

推荐答案

我唯一能想到的此刻范围内的子查询:

The only thing I can think of at the moment is a subquery inside the scope:

named_scope :failed_response, {
  :conditions => ["(SELECT passed FROM responses WHERE 
     responses.article_id = articles.id ORDER BY id DESC LIMIT 1) = ?", false]
}

我想有某种Rails的方式,是一个更好一点或没有子查询的方式,但我不认为它的​​时刻。希望这有助于虽然。 :)

I guess there is some kind of Rails way that is a bit nicer or a way without a subquery, but I can't think of it at the moment. Hope this helps though. :)

这篇关于转换一个简单的查询到RoR中一个棘手的命名范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆