将简单查询转换为 RoR 中棘手的命名范围

发布于 2024-10-10 21:40:21 字数 440 浏览 5 评论 0原文

我有一个简单的范围界定问题。我想将其作为一个范围:

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

因此,在文章模型上,我会有类似这样的内容:

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

问题是,我只想要最近响应失败的实例。我确信这是一种通过奇特的排序或某种嵌套查询来做到这一点的方法,但我被困住了。谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酷炫老祖宗 2024-10-17 21:40:21

目前我唯一能想到的是作用域内的子查询:

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

我猜想有某种Rails 方式更好一点或者没有子查询的方式,但我现在想不到。希望这会有所帮助。 :)

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]
}

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. :)

夏天碎花小短裙 2024-10-17 21:40:21

我想说的是,要说清楚而不是聪明。有一个实例方法返回该文章的last_reponse,然后有另一个实例方法返回布尔值,判断该值是真还是假。它可能不如单行 SQL 的名称范围那么快。但我仍然采用清晰的方式来实现更好的可维护性/理解。

I'd say to make it clear than clever. Have a instance method to return the last_reponse for that individual article and then have another instance method to return boolean of whether that's true or false. It may not be as fast as a name scope with single line of SQL. But I still do it the clear way for better maintainability/understanding.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文