ruby-on-rails - rails 5.1 : Passing in array to where query does not search across multiple values

标签 ruby-on-rails postgresql activerecord ruby-on-rails-5.1

我正在将我的 Rails 应用程序升级到 5.1.x。 我注意到,当我尝试查询时,例如:
Book.where(genre: ['mystery', 'romance']).count,
生成的SQL是
SELECT COUNT(*) FROM "books"WHERE "books"."genre"= $1 [["genre", "[\"mystery\",\"romance\"]"]]
而不是你所期望的:
SELECT COUNT(*) FROM "books"WHERE "books"."genre"IN ('mystery', 'romance')

有什么变化?有什么方法可以保持旧的行为吗? 5.1.3 并不表示此功能已更改: http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where

谢谢!

最佳答案

更新:发现我的问题!感谢罗伯特前几天的问题,我意识到我的问题是因为 genre作为字符串保存到数据库中,但用作 Genre目的。以前,我一直在使用 serialize :genre Genre , 但出于某种原因,它没有在 where 子句中正确使用正确的值。

我创建了一个新的 GenreType < ActiveRecord::Type并添加了 attribute :genre GenreType.new瞧!

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

关于ruby-on-rails - rails 5.1 : Passing in array to where query does not search across multiple values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892212/

相关文章:

php - Laravel 事件记录中的 Mysql 查询

ruby - 在保存记录之前创建关联

mysql - rails SQL 查询

ruby-on-rails - RoR Ransack 搜索问题

ruby-on-rails - FactoryGirl + Faker - 为数据库种子数据中的每个对象生成相同的数据

ruby - 连接到本地 linux 安装上的 postgres 数据库

postgresql - Rails 5 和 Postgres - 我可以在字段名称中使用 "?"吗?

ruby-on-rails - 使用 Ruby on Rails 批量更新

sql - 如何使用 DataGrip 在本地创建 postgreSQL 数据库

ruby-on-rails - RoR 4 中带验证的正则表达式