How do I write this scope to search for attributes on a nested model? (again)
OK,
I asked this question earlier today
How do I write a scope to search for attributes on a nested model?
and got a great answer on searching for attributes in nested models in Rails.
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('admis开发者_运维问答sions.discharge_time' => nil)
end
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.
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)
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/
精彩评论