Why is Rails is adding `OR 1=0` to queries using the where clause hash syntax with a range?

后端 未结 5 943
生来不讨喜
生来不讨喜 2020-12-17 10:04

The project that I\'m working on is using MySQL on RDS (mysql2 gem specifically).

When I use a hash of conditions including a range in a where statement

5条回答
  •  猫巷女王i
    2020-12-17 10:37

    I think you're seeing side effects of ruby personally.

    I think the better way to do what you're doing would be with

    2.0.0-p481@meri :008 > [*1..5]
     => [1, 2, 3, 4, 5]
    
    User.where(id: [*1..5]).to_sql
    "SELECT `users`.* FROM `users`  WHERE `users`.`id` IN (1, 2, 3, 4, 5)"
    

    As this creates an Array vs an Array with element 1 of class Range.

    OR

    use an explicit Range to trigger the BETWEEN in AREL.

    # with end element, i.e. exclude_end=false
    2.0.0-p481@meri :013 > User.where(id: Range.new(1,5)).to_sql
    => "SELECT `users`.* FROM `users`  WHERE (`users`.`id` BETWEEN 1 AND 5)"
    
    # without end element, i.e. exclude_end=true
    2.0.0-p481@meri :022 > User.where(id: Range.new(1, 5, true)).to_sql
     => "SELECT `users`.* FROM `users`  WHERE (`users`.`id` >= 1 AND `users`.`id` < 5)"
    

提交回复
热议问题