Is there a way to invert an ActiveRecord::Relation query?

前端 未结 4 715
太阳男子
太阳男子 2021-02-08 03:31

Let\'s say we have the following:

irb> Post.where(:hidden => true).to_sql
=> \"SELECT `posts`.* FROM `posts` WHERE posts.hidden = 1\"

4条回答
  •  别那么骄傲
    2021-02-08 04:04

    We can take Zabba's answer further by passing the inverted query back into ActiveRecord:

    table = Post.arel_table
    query = table[:hidden].eq(true).not # the inverted query, still ARel
    Post.where(query) # plug it back into ActiveRecord
    

    This will return ActiveRecord objects, as you would normally expect.

提交回复
热议问题