如何编写此范围来搜索嵌套模型上的属性?(再次) [英] How do I write this scope to search for attributes on a nested model? (again)
问题描述
好的,
我今天早些时候问过这个问题
I asked this question earlier today
并在 Rails 中搜索嵌套模型中的属性时得到了很好的答案.
and got a great answer on searching for attributes in nested models in Rails.
在上一个问题中,编写了一个范围来查找所有出院时间为 nil 的入院患者(感谢 tjwallace).
In the previous question a scope was written that found all patients that had an admission with a discharge_time of nil (Thanks tjwallace).
class Patient < ActiveRecord::Base
has_many :admissions
scope :admitted, includes(:admissions).where('admissions.discharge_time' => nil)
end
我现在要做的是编写一个名为 :discharged 的范围,该范围将进行搜索,返回所有至少有一次入院且出院时间不为零的患者.我试过以下;
What I'm trying to do now is to write a scope called :discharged, that will do a search that returns all patients that have at least one admission with a discharge_time that is not nil. I've tried the following;
scope :discharged, includes(:admissions).where('admissions.discharge_time <> ?', nil)
但这不会返回任何结果(并且数据库中肯定有应该通过正确编写的搜索找到的患者).任何帮助将不胜感激.
but this returns no results (and there are definitely patients in the database that should be found by a correctly written search). Any help will be greatly appreciated.
推荐答案
这是因为在 SQL 中你不能真正将任何东西与 NULL 进行比较,你需要这样写:
This is because in SQL you can't really compare anything to NULL, you need to write something like this:
scope :discharged, includes(:admissions).where('admissions.discharge_time is not ?', nil)
这是对这种 SQL 行为的一个很好的解释:http://www.xaprb.com/blog/2006/05/18/why-null-never-compares-false-to-anything-in-sql/
Here is a nice explanation of this SQL behavior: http://www.xaprb.com/blog/2006/05/18/why-null-never-compares-false-to-anything-in-sql/
这篇关于如何编写此范围来搜索嵌套模型上的属性?(再次)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!