ruby-on-rails - postgresql 中的“Where-in”查询显示相同结果的两个不同查询

标签 ruby-on-rails postgresql

我有如下的事件记录关联关系。

@tasks =  #<ActiveRecord::AssociationRelation [#<Task id: 3130, title: "Commit to at least one small win today", content: "When I check-in on the app it lets me acknowledge m...",created_at: "2016-01-13 01:36:15", updated_at: "2016-01-13 04:47:57", state: "active", #<Task id: 3131, title: "Purposefully walk 3 minutes ", content: "More than just my ordinary day, I choose 5 minutes ...", created_at: "2016-01-13 04:52:32", updated_at: "2016-01-13 04:56:22", state: "active", #<Task id: 3132, title: "1km Walk or Run by Sunday", content: "I pick a direction, start with a 10 minute warm up,...", created_at: "2016-01-13 04:56:05", updated_at: "2016-01-13 04:56:05", state: "active",#<Task id: 3249, title: "1km Walk or Run by Wednesday", content: "I pick a direction, start with a 10 minute warm up,...", created_at: "2016-01-24 23:23:34", updated_at: "2016-01-24 23:23:34", state: "active"]> 


@array = []

@tasks.each do |task|
if (condition)
  @array << task.id
end  

@tasks = @tasks.where.not('tasks.id in (?)',@array)

如果我在@array 中得到任何非空值,
上述条件工作正常。

如果我得到@array = [] i,e 空数组,
@tasks = @tasks.where.not('tasks.id in (?)',@array) 没有给我正确的结果。

此外,@tasks = @tasks.where('tasks.id in (?)',@array),当数组为 [] 时,通过删除 'not' 给出相同的结果p>

 @habits = @habits.where.not('habits.id in (?)',@id_s)  ====> output => []
 @habits = @habits.where('habits.id in (?)',@id_s)  ====> output => []

They both are returning same optput if @id_s is []

为什么这些查询针对两种不同的条件返回相同的值?

最佳答案

如果您的 Rails 版本是最新的,您应该切换到哈希表示法,它可以为您处理所有特殊情况,例如空数组:

@tasks = @tasks.where.not(id: @array)

关于ruby-on-rails - postgresql 中的“Where-in”查询显示相同结果的两个不同查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35057669/

相关文章:

sql - 关于部分键和数据库表索引的问题

html - 如何使用样式标签在我的 css 中使用 ruby​​ on rails?

ruby-on-rails - 在 Heroku 上运行 rake 任务时禁用 NewRelic 日志

ruby-on-rails - Rails 控制台 sql 查询只返回 true

sql - 具有相同名称列的连接表上的 Rails ".pluck"返回一个值,然后返回 nil

sql - 从 generate_series(int, int) 函数更新表 Postgres 9.0

ruby-on-rails - Ruby 类名前的双冒号?

postgresql - 将现有的 SMALLINT 数据转换为 INTEGER?

sql - 在 PostgreSQL 中选择而不创建新表

postgresql - Postgres 连接问题