In a Rails 4 app, I have related models Applicant and Trademark, with the latter searchable using Searchkick:
class Applicant < ActiveRecord::Base
has_many :trademarks
end
class Trademark < ActiveRecord::Base
belongs_to :applicant
searchkick
end
I'm trying to find instances of Trademark which do not have an Applicant. Using standard ActiveRecord the below query works, and returns the Trademark without an Applicant:
Trademark.where(applicant: nil).count
(1.7ms) SELECT COUNT(*) FROM "trademarks" WHERE "trademarks"."applicant_id" IS NULL
=> 1
How can I run the equivalent query with the addition of SearchKick?
# these queries run correctly and show that SearchKick is working
Trademark.search "*" # => 7 records
Trademark.search "*", where: {status: "Removed"} # => 5 records
# When trying to search for applicant == nil, the search fails:
# this returns 7 records, instead of the 1 expected result
Trademark.search "*", where: {applicant: nil}
# this returns 0 records, instead of the 1 expected result
Trademark.search "*", where: {applicant_id: nil}
How can I use a where clause for a nil value in SearchKick?
The answer came from Andrew Kane, the developer of the SearchKick gem.
I needed to run Trademark.reindex()
to synchronise the database and ElasticSearch. After that the syntax Trademark.search "*", where: {applicant_id: nil}
worked as expected.