'其中,在'在postgresql中查询显示相同结果的两个不同查询

时间:2016-01-28 09:34:37

标签: 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,那么空数组,
@tasks = @ tasks.where.not(&#39; tasks.id in(?)&#39;,@ array)没有给我正确的结果。

另外,@ tasks = @ tasks.where(&#39; tasks.id in(?)&#39;,@ array),这个条件是删除&#39; not&#39;当数组为[]

时,当不存在时给出相同的结果
 @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 []

为什么这些查询会为两个不同的条件返回相同的值?

1 个答案:

答案 0 :(得分:0)

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

@tasks = @tasks.where.not(id: @array)
相关问题