将简单查询转换为 RoR 中棘手的命名范围
我有一个简单的范围界定问题。我想将其作为一个范围:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
目前我唯一能想到的是作用域内的子查询:
我猜想有某种Rails 方式更好一点或者没有子查询的方式,但我现在想不到。希望这会有所帮助。 :)
The only thing I can think of at the moment is a subquery inside the scope:
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. :)
我想说的是,要说清楚而不是聪明。有一个实例方法返回该文章的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.