This project is archived and is in readonly mode.
Optional NULL via condition hash
Reported by pelzrutsche | July 20th, 2008 @ 02:55 PM | in 2.x
The following code:
Page.find(:all, :conditions => { :author => ['Anonymous', nil]})
resutls in an SQL query like this:
[...] WHERE `author` IN ('Anonymous', NULL)
However, it does not return any pages with author = nil/NULL (using MySQL).
I fixed this by factroing out
active_record/base.rb in sanitize_sql_hash_for_conditions
"#{table_name}.#{connection.quote_column_name(attr)} #{attribute_condition(value)}"
into a new method, advanced_attribute_condition. It checks for an array-argument including nil and builds the SQL snippet accordingly. For example:
{ :author => ['Anonymous', nil] } #=> [...] WHERE (author = 'Anonymous' OR author IS NULL)
{ :type => ['a', 'b', nil] } #=> [...] WHERE (type IN ('a', 'b') OR type IS NULL)
This may also be handy when working with LEFT OUTER JOIN, as conditions affecting a associated table result in a RecordNotFound if no matching record can be found in it.
Comments and changes to this ticket
-
Pratik July 20th, 2008 @ 06:37 PM
- State changed from new to wontfix
- Assigned user set to Pratik
I understand that this is an issue. But I don't think this corner case justifies the added complexity in the code.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>