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

前端 未结 4 719
太阳男子
太阳男子 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:25

    In rails 4 there is not suffix for this purpose:

    Post.where.not(hidden: true).to_sql
    # => SELECT FROM `posts` WHERE `posts`.`hidden` != 1
    

    In rails 3 you can use squeel gem. It gives many usefull features. And with it you can write:

    Post.where{ hidden != true }.to_sql
    # => SELECT FROM `posts` WHERE `posts`.`hidden` != 1
    

提交回复
热议问题