Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord appends 'AND (1=0)' to end of queries

I've been playing around in the rails console trying to get things to work, and I notice that one of my queries keeps returning nil when it shouldn't. Upon looking at the generated SQL query I notice that it has AND (1=0) appended to it each time. This is kind of annoying, and I'm not sure why it's doing this.

Note: Using the actable gem.

Steps to reproduce:

(After connecting to tables in rails console)

2.1.2 :xxxx > @parent = Parent.take Parent Load (38.1ms)  SELECT  `parents`.* FROM `parents`  LIMIT 1  => #<Parent id: 37, ...>  2.1.2 :xxxx > @child = Child.where(id: @parent.actable_id) SQL (0.7ms)  SELECT `childs`.`id` AS t0_r0, `childs`.`attribute` AS t0_r1, FROM `childs` ... LEFT OUTER JOIN `parents` ON `parents`.`actable_id` = `childs`.`id` AND `parents`.`actable_type` = 'child type' WHERE `childs`.`id` = 20 AND (1=0)  => #<ActiveRecord::Relation []> 

Why is this happening? How do I make it stop?

like image 866
0112 Avatar asked Sep 12 '14 21:09

0112


People also ask

What is the meaning of where 1 0 in SQL?

A query like this can be used to ping the database. The clause: WHERE 1=0. Ensures that non data is sent back, so no CPU charge, no Network traffic or other resource consumption. A query like that can test for: server availability.

What is eager loading in rails?

Eager loading lets you preload the associated data (authors) for all the posts from the database, improves the overall performance by reducing the number of queries, and provides you with the data that you want to display in your views, but the only catch here is which one to use.

What is the use of 1 1 in SQL?

If you have worked with SQL databases before, you might have come across the statement WHERE 1=1. It is a common statement that is used to return all the records from a given table. The statement where 1=1 in SQL means true. It is the same operation as running the select statement without the where clause.

What is Ruby ActiveRecord?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


1 Answers

Rails will generate SQL like AND (1=0) when you query for a column whose value is in an empty array:

Child.where(id: []) 

Intuitively, you'd expect that to generate SQL like SELECT * FROM children WHERE id IN (), but () isn't actually valid SQL. Since no rows will match that query, though, Rails works around this by generating an equivalent query that also returns no rows:

SELECT * FROM children WHERE 1=0; 
like image 198
MaxGabriel Avatar answered Sep 22 '22 10:09

MaxGabriel