我在尝试以优雅的方式处理 NOT IN 查询(使用 Rails 4/Postgres,以供引用)时遇到问题。我正在尝试获取某个模型的所有对象的列表,这些对象没有出现在某个实例的连接表中。它有效,当您尝试使用空数组进行 NOT IN 查询时,它会抛出错误,因为您无法查找 NOT IN NULL。
下面的代码现在可以工作了,但是有没有比使用不直观的条件来生成伪空对象更好的方法呢?
def characters_selected
self.characters_tagged.pluck(:name)
end
def remaining_characters
characters = self.characters_selected
characters = ["SQL breaks if this is null"] if characters.empty?
# this query breaks on characters_selected == [] without the above line
Character.where("name NOT IN (?)", characters )
end
最佳答案
这是 ActiveRecord 方式:
def remaining_characters
characters = self.characters_selected
Character.where.not(:name => characters)
end
什么时候characters.empty? where 子句变为“WHERE (1=1)”。
关于ruby-on-rails - .where.not 空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27115562/