How do I write this scope to search for attributes on a nested model? (again)

青春壹個敷衍的年華 提交于 2019-12-12 06:31:40

问题


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('admissions.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.


回答1:


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/



来源:https://stackoverflow.com/questions/5686101/how-do-i-write-this-scope-to-search-for-attributes-on-a-nested-model-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!