Rails 5.1: Passing in array to where query does not search across multiple values

279 views Asked by At

I'm in the process of upgrading my Rails app to 5.1.x. I've noticed that when I try a query such as:
Book.where(genre: ['mystery', 'romance']).count,
the SQL generated is
SELECT COUNT(*) FROM "books" WHERE "books"."genre" = $1 [["genre", "[\"mystery\", \"romance\"]"]]
instead of what you'd expect:
SELECT COUNT(*) FROM "books" WHERE "books"."genre" IN ('mystery', 'romance')

What has changed? Is there some way to keep the old behavior? The 5.1.3 doesn't suggest that this functionality has changed: http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where

Thanks!

1

There are 1 answers

0
bhbbby On

Update: Found my problem! Thanks to Robert's question the other day, I realized my problem is because genre is saved to the DB as a string but is used as a Genre object. Previously, I'd been using serialize :genre Genre, but for some reason it wasn't using the right values in the where clause properly.

I created a new GenreType < ActiveRecord::Type and added attribute :genre GenreType.new and voila!

http://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html