Skip to content

Instantly share code, notes, and snippets.

@danmayer
Created September 29, 2011 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danmayer/1250980 to your computer and use it in GitHub Desktop.
Save danmayer/1250980 to your computer and use it in GitHub Desktop.
ActiveRecord Association objects make no sense (bug in any?)
# this is rails 2.3.x so perhaps it has been fixed but any on a empty AR association object that has [] returns true.
# after being inspected or to_s it returns false (as it should
# rails console
[].any? => false
none = ar_object.association_objects (like Person.find(2).posts where there are no posts) => []
none.any? => false
none.ancestors.map(&:to_s).sort == (from Rails.development.log none.ancestors.map(&:to_s).sort ) => true
(just to make sure all the same things are loaded -> "ActiveRecord::AssociationPreload", "ActiveRecord::Associations", "ActiveRecord::AttributeMethods"... and many more)
# rails production or development log
[].any? => false
none = ar_object.association_objects (like Person.find(2).posts where there are no posts) => []
************************************* the problem *************************************
none.any? => true
none.inspect; none.any? => false
none.to_s; none.any? => false
# note you can't actually do 'Rails.logger.info any?', and get true, because rails logger calls .to_s
# so to log the issue do:
if none.any?
Rails.logger "none.any? is true"
else
Rails.logger "none.any? is false"
end
# Why would it ever return true?, why would calling inspect, make it correctly return false?
# Where is the call being intercepted, what is going on, where am I and how did I get here... Bah
# SOLUTION:
# none.present? works in all cases and my solution was just to switch to using that, but I am still baffled.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment