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?
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.
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.
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 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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With